tarjan缩点应用 Popular Cows POJ - 2186

简单应用,这个问题因为数据挺大的所有暴力求肯定不行,缩点就是把一部分点变成一个,这部分点是一样的,这个就是把这个图中那些强连通点变成一个,因为一个强连通分量一点过互相崇拜,所有可以把他们缩点。然后就是缩点之后如果一个点还去崇拜其他点那么它一定不会被它崇拜的点崇拜(否则就会缩成一个点),那么就是求那个没有去崇拜别人的点。如果就有一个的话,那么就是这个大点里面小点的个数,如果有两个及以上就说明有两个点没联通,所有就是没有被全部崇拜的。

#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<stack>

using namespace std;

const int maxn = 1e4 + 10;
struct node
{
    int next, to;
};

node edge[500010];
int dfn[maxn], low[maxn], color[maxn], vis[maxn], du[maxn], head[maxn], cnt[maxn];
int tot, deep, num;
stack<int>Q;
void add(int u, int to)
{
    edge[tot] = (node){head[u], to};
    head[u] = tot++;
}
void tarjan(int x)
{
    vis[x] = 1;
    dfn[x] = ++deep;
    low[x] = dfn[x];
    Q.push(x);
    for(int i = head[x]; ~i; i = edge[i].next)
    {
        int to = edge[i].to;
        if(!dfn[to])
        {
            tarjan(to);
            low[x] = min(low[x], low[to]);
        }
        else
        {
            if(vis[to])
            {
                low[x] = min(low[x], low[to]); // dfn[to]
            }
        }
    }
    if(dfn[x] == low[x])
    {
        color[x] = ++num;
        vis[x] = 0; // 别漏了
        while(Q.top() != x)
        {
            color[Q.top()] = num;
            vis[Q.top()] = 0;
            Q.pop();
        }
        Q.pop();
    }
}

int main()
{
    int n, m;
    tot = 0;
    memset(head, -1, sizeof(head));
    num = 0, deep = 0;
    scanf("%d%d", &n, &m);
    for(int i = 0; i < m; i++)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        add(u, v);
        //du[u]++;
    }
    for(int i = 1; i <= n; i++)
    {
        if(!dfn[i])
        {
            tarjan(i);
        }
    }
    for(int i = 1; i <= n; i++)
    {
        for(int j = head[i]; ~j; j = edge[j].next)
        {
            int to = edge[j].to;
            if(color[i] != color[to])
            {
                du[color[i]]++;
            }
        }
        cnt[color[i]]++;
    }
    int tmp = 0, ans = 0;
    for(int i = 1; i <= num; i++)
    {
        if(du[i] == 0)
        {
            tmp++;
            ans = cnt[i];
        }
    }
    if(tmp == 0)
        printf("0\n");
    else
    {
        if(tmp > 1)
            printf("0\n");
        else
            printf("%d\n", ans);
    }
    return 0;
}

发布了40 篇原创文章 · 获赞 13 · 访问量 848

猜你喜欢

转载自blog.csdn.net/weixin_43891021/article/details/102783657
今日推荐