Loading

SPOJ-TFRIENDS True Friends

True Friends

判断所有强连通块的数量

tarjan 模板

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <vector>
#include <string>
using namespace std;
const int maxn = 110;
vector<int>gra[maxn];
int low[maxn], dfn[maxn], tp = 0;
int scc[maxn], cnt_scc = 0;
int vis[maxn];
stack<int>st;

void tarjan(int now)
{
    vis[now] = 1;
    st.push(now);
    dfn[now] = low[now] = ++tp;
    for(int nex : gra[now])
    {
        if(dfn[nex] == 0)
        {
            tarjan(nex);
            low[now] = min(low[now], low[nex]);
        }    
        else if(vis[nex])
            low[now] = min(low[now], low[nex]);
    }
    if(low[now] == dfn[now])
    {
        cnt_scc++;
        while(st.top() != now)
        {
            int x = st.top();
            vis[x] = 0;
            scc[x] = cnt_scc;
            st.pop();
        }
        vis[now] = 0;
        scc[now] = cnt_scc;
        st.pop();
    }
}

void init(int n)
{
    for(int i=0; i<=n; i++) low[i] = dfn[i] = scc[i] = 0;
    tp = cnt_scc = 0;
    for(int i=0; i<=n; i++) gra[i].clear();
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        init(n);
        for(int i=1; i<=n; i++)
        {
            string s;
            cin >> s;
            for(int j=0; j<s.length(); j++)
            {
                if(s[j] == 'Y')
                    gra[i].push_back(j + 1);
            }
        }
        for(int i=1; i<=n; i++)
            if(dfn[i] == 0) tarjan(i);
        cout << cnt_scc << endl;
    }
}

posted @ 2022-08-12 14:00  dgsvygd  阅读(32)  评论(0编辑  收藏  举报