​Popular Cows​​​ Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 42216 Accepted: 17135
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.


// #include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<vector>
#include<deque>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5+7;
int V;
int used[MAXN], cmp[MAXN];
vector<int> G[MAXN];
vector<int> rG[MAXN];
vector<int> vs;

void add_edge(int x, int y)
{
G[x].push_back(y);
rG[y].push_back(x);
}

void dfs(int v)
{
used[v] = true;
for(int i=0;i<(int)G[v].size();++i)
if(!used[G[v][i]]) dfs(G[v][i]);
vs.push_back(v);
}
void rdfs(int v, int k)
{
used[v] = true;
cmp[v] = k;
for(int i=0;i<(int)rG[v].size();++i)
if(!used[rG[v][i]]) rdfs(rG[v][i],k);
}
int scc()
{
memset(used, 0, sizeof(used));
memset(cmp, 0, sizeof(cmp));
vs.clear();
for(int i=0;i<V;++i)
if(!used[i]) dfs(i);
memset(used, 0, sizeof(used));
int k=0;
for(int i=vs.size()-1; i>=0; --i)
if(!used[vs[i]]) rdfs(vs[i], k++);
return k;
}

int main()
{
// freopen("../in.txt","r",stdin);
// freopen("../out.txt","w",stdout);
int N, M;
while(cin>>N>>M)
{
V = N;
for(int i=0;i<=N;++i)
{
G[i].clear();
rG[i].clear();
}
int x,y;
for(int i=0;i<M;++i)
{
cin>>x>>y;
add_edge(x-1, y-1);
}
int n = scc();
int num = 0;
int u = 0;
for(int i=0;i<V;++i)//拓扑序列最后的一个才有可能是可行解
{
if(cmp[i]==n-1)
{
num++;
u = i;
}
}
memset(used, 0, sizeof(used));
rdfs(u, 0);
for(int i=0;i<V;++i)
if(!used[i])
{
num = 0;
break;
}
cout<<num<<endl;

}
return 0;
}