洛谷 P2863 tarjan求强连通分量个数

题意:给定一个n个点,m条边的有向图,求大小大于1的强连通分量个数

tarjan模板

#include
#include
#define maxn 10010
#define maxm 50010

int time = 0, top = 0;
int l = 0;
int last[maxn], dfn[maxn], low[maxn], belong[maxn];
int size[maxn], z[maxn];
int vis[maxn];
int other[maxm], pre[maxm];

int min(int x, int y){
    return(x < y ? x : y);
}

void connect(int x, int y){
    l++;
    pre[l] = last[x];
    last[x] = l;
    other[l] = y;
}

void dfs(int x) {
    int p, q;
    int cur;

    time++;
    vis[x] = 1;
    dfn[x] = time;
    low[x] = time;
    top++;
    z[top] = x;
    //
    q = last[x];
    while (q != 0) {
        p = other[q];
        if (dfn[p] == 0) {
            dfs(p);
            low[x] = min(low[x], low[p]);
        } else if (vis[p] == 1) low[x] = min(low[x], dfn[p]);
        q = pre[q];
    }
//
    if (dfn[x] == low[x]) {
        cur = -1;
        while (cur != x) {
            cur = z[top];
            belong[cur] = x;
            vis[cur] = 0;
            size[belong[cur]]++;
            top--;
        }
    }

}

int main() {
    int i;
    int n, m, x, y;
    int ans = 0;

    memset(dfn, 0, sizeof(dfn));
    memset(vis, 0, sizeof(vis));
    memset(size, 0, sizeof(size));

    scanf("%d %d", &n, &m);
    for (i = 1; i <= m; i++) {
        scanf("%d %d", &x, &y);
        connect(x, y);
    }
    for (i = 1; i <= n; i++)
        if (dfn[i] == 0) dfs(i);
    for (i = 1; i <= n; i++)
        if ((belong[i] == i) && (size[belong[i]] > 1))  ans++;
    printf("%d\n", ans);
    return 0;
}

 

你可能感兴趣的:(tarjan,模板)