Description
Input
Output
一個數,即有多少頭牛被所有的牛認爲是受歡迎的。
Sample Input
1 2
2 1
2 3
Sample Output
HINT
100%的數據N<=10000,M<=50000
這個要求強聯通分量+縮點,用鏈式結構存儲才行。
看碼:
#include<stdio.h>
int idx;
int ans2;
int low[50001];
int deep[50001],idx2,cnt,t;
int head[50001];
int x[50001],y[50001],z[50001];
int top,f[50001];
int ans[50001];
int num[50001],n,m;
int inz[50001];
int to[50001];
int next[50001];
int min(int x,int y)
{
if(x<y)
return x;
return y;
}
void addedge(int x,int y)
{
to[++idx]=y;
next[idx]=head[x];
head[x]=idx;
}
void tarjan(int x)
{
low[x]=deep[x]=++cnt,z[++top]=x,inz[x]=1;
for(int i=head[x];i;i=next[i])
{
if(!deep[to[i]])
{
tarjan(to[i]);
low[x]=min(low[x],low[to[i]]);
}
else if(inz[to[i]]&&low[x]>deep[to[i]])
low[x]=deep[to[i]];
}
if(low[x]==deep[x])
{
idx2++;
do
{
t=z[top--];
ans[idx2]++;
inz[t]=0;
f[t]=idx2;
}while(x!=t);
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x[i],&y[i]);
addedge(x[i],y[i]);
}
for(int i=1;i<=n;i++)
if(!deep[i])
tarjan(i);
for(int i=1;i<=m;i++)
if(f[x[i]]!=f[y[i]])
num[f[x[i]]]++;
for(int i=1;i<=idx2;i++)
if(num[i]==0)
{
if(ans2!=0)
{
printf("0");
return 0;
}
ans2=i;
}
printf("%d",ans[ans2]);
}