Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 22189 | Accepted: 9076 |
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.
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.
Source
强连通分量缩点,然后拓扑序最大的强连通分量反向搜索,看能不能遍历到所有的结点。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack> using namespace std; int N,M;
const int MAX_N = ;
const int edge = ;
stack<int> S;
int pre[MAX_N],low[MAX_N],cmp[MAX_N];
int first[MAX_N],Next[edge],v[edge];
int rfirst[MAX_N],rNext[edge],rv[edge];
int dfs_clock,scc_cnt; void dfs(int u) {
low[u] = pre[u] = ++dfs_clock;
S.push(u);
for(int e = first[u]; e != -; e = Next[e]) {
if(!pre[ v[e] ]) {
dfs(v[e]);
low[u] = min(low[u],low[ v[e] ]);
} else if(!cmp[ v[e] ]) {
low[u] = min(low[u],pre[ v[e] ]);
}
} if(low[u] == pre[u]) {
++scc_cnt;
for(;;) {
int x = S.top(); S.pop();
cmp[x] = scc_cnt;
if(x == u) break;
}
}
} void scc() {
dfs_clock = scc_cnt = ;
memset(cmp,,sizeof(cmp));
memset(pre,,sizeof(pre));
for(int i = ; i <= N; ++i) {
if(!pre[i]) dfs(i);
}
} void dfs1(int u) {
pre[u] = ;
for(int e = rfirst[u]; e != -; e = rNext[e]) {
if(!pre[ rv[e] ]) {
dfs1(rv[e]);
}
}
} int solve() {
scc();
memset(pre,,sizeof(pre));
int u,ans = ;
for(int i = ; i <= N; ++i)
if(cmp[i] == ) {
u = i;
++ans;
} dfs1(u);
for(int i = ; i <= N; ++i) {
if(!pre[i]) return ;
}
return ans;
} void add_edge(int id,int u) {
int e = first[u];
Next[id] = e;
first[u] = id;
} void radd_edge(int id,int u) {
int e = rfirst[u];
rNext[id] = e;
rfirst[u] = id;
}
int main()
{
// freopen("sw.in","r",stdin);
scanf("%d%d",&N,&M);
for(int i = ; i <= N; ++i) rfirst[i] = first[i] = -;
for(int i = ; i < M; ++i) {
int u;
scanf("%d%d",&u,&v[i]);
rv[i] = u;
add_edge(i,u);
radd_edge(i,v[i]);
} printf("%d\n",solve());
return ;
}