1. 程式人生 > >Popular Cows

Popular Cows

space 表示 ansi lin names and eve ack push

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.

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

Hint

Cow 3 is the only cow of high popularity. 每一頭牛的願望就是變成一頭最受歡迎的牛。現在有N頭牛,給你M對整數(A,B),表示牛A認為牛B受歡迎。 這 種關系是具有傳遞性的,如果A認為B受歡迎,B認為C受歡迎,那麽牛A也認為牛C受歡迎。你的任務是求出有多少頭 牛被所有的牛認為是受歡迎的。 先用tarjan求出每個強連通分量,再縮點,統計每個點的出度,如果有且只有1個出度為0的點,就輸出這個點包含的節點數,否則輸出0.
 1
#include<iostream> 2 #include<algorithm> 3 #include<vector> 4 #include<stdio.h> 5 #include<stdlib.h> 6 #include<string.h> 7 #define MaxNum 10005 8 using namespace std; 9 10 int n,m; 11 vector<int > edge[MaxNum]; 12 int dfn[MaxNum],low[MaxNum]; 13 int time=0; 14 int color=0; 15 int allColor[MaxNum]={0}; 16 int allSum[MaxNum]={0}; 17 int stack[MaxNum],top=0; 18 bool vis[MaxNum]; 19 20 void targan(int d){ 21 vis[d]=true; 22 dfn[d]=++time; 23 low[d]=time; 24 stack[++top]=d; 25 for(int i=0;i<edge[d].size();++i) 26 { 27 if(!vis[edge[d][i]]) 28 { 29 targan(edge[d][i]); 30 low[d]=min(low[d],low[edge[d][i]]); 31 } 32 else low[d]=min(low[d],dfn[edge[d][i]]); 33 } 34 35 if(dfn[d]==low[d]) 36 { 37 ++color; 38 while(stack[top]!=d) 39 { 40 allColor[stack[top--]]=color; 41 allSum[color]++; 42 } 43 44 allColor[stack[top--]]=color; 45 allSum[color]++; 46 } 47 } 48 49 int out[MaxNum]={0}; 50 int main() 51 { 52 cin>>n>>m; 53 for(int i=1;i<=m;++i) 54 { 55 int x,y; 56 cin>>x>>y; 57 edge[x].push_back(y); 58 } 59 60 memset(vis,false,sizeof(vis)); 61 for(int i=1;i<=n;++i) 62 if(!vis[i]) 63 targan(i); 64 65 66 for(int i=1;i<=n;++i) 67 for(int j=0;j<edge[i].size();++j) 68 if(allColor[i]!=allColor[edge[i][j]]) 69 out[allColor[i]]++; 70 71 int total=0;int ans=0; 72 for(int i=1;i<=color;++i) 73 if(out[i]==0) 74 { 75 total++; 76 ans=allSum[i]; 77 } 78 79 if(total>1) ans=0; 80 cout<<ans<<endl; 81 return 0; 82 83 }

Popular Cows