Description
每一头牛的愿望就是变成一头最受欢迎的牛。现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎。 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认为牛C受欢迎。你的任务是求出有多少头牛被所有的牛认为是受欢迎的。
Input
第一行两个数N,M。 接下来M行,每行两个数A,B,意思是A认为B是受欢迎的(给出的信息有可能重复,即有可能出现多个A,B)
Output
一个数,即有多少头牛被所有的牛认为是受欢迎的。
Sample Input
3 3
1 2
2 1
2 3
Sample Output
1
HINT
100%的数据N<=10000,M<=50000
Source
tarjan找强连通分量,缩点。
本来我想统计缩点后每个连通分量的入度,结果要判重边,空间开不起…
其实可以统计出度。统计好每个连通分量的出度,再统计出度为0的连通分量个数,若为1则输出这个强连通分量的大小,else输出0 。
正确性:
若某个强连通分量的出度不为0,则它连向的点都不会连会原来的强连通分量,如果连回去则他们就在同一个分量了。所以出度不为0的强连通分量必定不是答案。
若出度为0的强连通分量有好几个,则他们互相独立,互相不连边,那答案就是0。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
const int size=100010;
int head[size],nxt[size],to[size],tot=0;
void build(int f,int t)
{
to[++tot]=t;
nxt[tot]=head[f];
head[f]=tot;
}
int low[size],dfn[size],dfs_clock=0;
int scccnt=0,sccnum[size],scctong[size];
stack<int> s;
void dfs(int u)
{
dfn[u]=low[u]=++dfs_clock;
s.push(u);
for(int i=head[u];i;i=nxt[i])
{
int v=to[i];
if(!dfn[v])
{
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(!sccnum[v])
{
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u])
{
scccnt++;
while(233)
{
int x=s.top(); s.pop();
sccnum[x]=scccnt;
scctong[scccnt]++;
if(x==u) break;
}
}
}
int n,m;
int ff[size],tt[size],cd[size];
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&ff[i],&tt[i]);
build(ff[i],tt[i]);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i]) dfs(i);
}
for(int i=1;i<=m;i++)
{
if(sccnum[ff[i]]!=sccnum[tt[i]])
{
cd[sccnum[ff[i]]]++;
}
}
int ans=0,tot=0;
for(int i=1;i<=scccnt;i++)
{
if(cd[i]==0)
{
ans+=scctong[i];
tot++;
}
}
if(tot==1) printf("%d",ans);
else printf("%d",0);
return 0;
}