求强连通分量数量

Every cow’s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
Input

  • Line 1: Two space-separated integers, N and M

  • Lines 2…1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
    Output

  • Line 1: A single integer that is the number of cows who are considered popular by every other cow.
    Sample Input
    3 3
    1 2
    2 1
    2 3
    Sample Output
    1

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 205*2;
int n,e,cnt,ans,top;
vector<int> G[maxn];
int dfn[maxn];//在dfs时第几个被搜到
int low[maxn];//这个点及其子孙节点的dfn值的最小值
int Stack[maxn];//当前所有可能构成强连通分量的点
bool vis[maxn];//表示一个点是否在Stack数组中

void tarjan(int u)
{
    int v;
    low[u] = dfn[u] = ++cnt;
    Stack[top++] = u;
    vis[u] = true;
    for(int i=0; i<G[u].size(); i++)
    {
        v = G[u][i];
        if(!dfn[v])
        {
            tarjan(v);
            low[u] = min(low[u],low[v]);
        }
        else
        {
            if(vis[v])
            low[u] = min(low[u],low[v]);
        }
    }
    if(low[u] == dfn[u])
    {
        ans++;
        do
        {
            v = Stack[--top];
            vis[v] = false;
        }
        while(v != u);
    }
}

void solve()
{
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(vis,false,sizeof(vis));
    cnt = top = ans = 0;
    for(int i=0; i<n; i++)
    {
        if(!dfn[i])
            tarjan(i);
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&e);
        for(int i=0; i<n; i++)
            G[i].clear();
        for(int i=1; i<=e; i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
        }
        solve();
        printf("%d",ans);
        if(T)
            printf("\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值