Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24533 | Accepted: 10067 |
Description
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.
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.
* 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
Hint
Cow 3 is the only cow of high popularity.
此题需先将强连通缩点得到DAG图,之后如果DAG中有1个以上的出度为0的点,则不符合题意,因为这些点不可能去认为别的点popular。而如果只有一个点出度为0,那么我们根据拓扑序列可以很明显观察到拓扑序最后一个点必然可以从前面任何一个点(因为这些点是有出度的)达到,这里从后往前推,数学归纳一些就知道了。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 10010
using namespace std;
struct edge{
int t1,t2,nx1,nx2;
}p[100010];
int hd1[Maxn];
int hd2[Maxn];
int tot;
void addedge(int a,int b){
p[tot].t1=b;
p[tot].nx1=hd1[a];
hd1[a]=tot++;
p[tot].t2=a;
p[tot].nx2=hd2[b];
hd2[b]=tot++;
}
int st[Maxn];
int belong[Maxn];
int vis[Maxn];
int top;
int scc;
void dfs1(int u){
vis[u]=1;
for(int i=hd1[u];i!=-1;i=p[i].nx1){
int v=p[i].t1;
if(!vis[v]) dfs1(v);
}
st[++top]=u;
}
void dfs2(int u){
vis[u]=1;
belong[u]=scc;
for(int i=hd2[u];i!=-1;i=p[i].nx2){
int v=p[i].t2;
if(!vis[v]) dfs2(v);
}
}
int kosaraju(int n){
top=scc=0;
memset(vis,0,sizeof vis);
for(int i=1;i<=n;i++)
if(!vis[i]) dfs1(i);
memset(vis,0,sizeof vis);
for(int i=top;i>0;i--)
if(!vis[st[i]]){
scc++;
dfs2(st[i]);
}
return scc;
}
int indeg[Maxn];
int main()
{
int n,m,a,b;
while(~scanf("%d%d",&n,&m)){
memset(hd1,-1,sizeof hd1);
memset(hd2,-1,sizeof hd2);
tot=0;
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
addedge(a,b);
}
kosaraju(n);
memset(indeg,0,sizeof indeg);
for(int i=1;i<=n;i++){
for(int j=hd1[i];j!=-1;j=p[j].nx1)
if(belong[i]!=belong[p[j].t1]) indeg[belong[i]]=1;
}
int cnt=0,res;
for(int i=1;i<=scc;i++)
if(!indeg[i]) {res=i;cnt++;}
if(cnt>1) puts("0");
else{
cnt=0;
for(int i=1;i<=n;i++)
if(belong[i]==res) cnt++;
printf("%d\n",cnt);
}
}
return 0;
}