Popular Cows
Time Limit: 2000MS
Memory Limit: 65536K
Total Submissions: 40372
Accepted: 16439
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.
Source
USACO 2003 Fall
题意:如果牛A认为牛B比较受欢迎,牛B认为牛C受欢迎,那么牛A也认为牛C比较受欢迎。
寻找最受欢迎的牛。
题解:寻找连通分支,出的为0 的牛就是最受欢迎的牛,若果只有一个那么就可以输出他有个数,否则输出0.
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 10005;
typedef vector<int> vec;
int n,m;
int low[maxn],dfn[maxn],belong[maxn];
int du[maxn],inStack[maxn],Stack[maxn];
int num[maxn];
vec edge[maxn];
int scc,index,top;
void tarjan(int u)
{
low[u] = dfn[u] = ++index;
Stack[top++] = u;
inStack[u] = 1;
int len = edge[u].size();
int v;
for(int i=0;i<len;i++){
v = edge[u][i];
if(!dfn[v]){
tarjan(v);
low[u] = min(low[u],low[v]);
}
else if(inStack[v]){
low[u] = min(low[u],low[v]);
}
}
if(dfn[u] == low[u]){
scc++;
do{
v = Stack[--top];
inStack[v] = 0;
belong[v] = scc;
num[scc]++;
}while(u!=v);
}
}
void sovle()
{
memset(inStack,0,sizeof(inStack));
memset(dfn,0,sizeof(dfn));
memset(belong,0,sizeof(belong));
memset(num,0,sizeof(num));
memset(du,0,sizeof(du));
index = top = scc = 0;
for(int i=1;i<=n;i++){
if(!dfn[i]){
tarjan(i);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
int tmp1,tmp2;
for(int i=0;i<m;i++){
scanf("%d%d",&tmp1,&tmp2);
edge[tmp1].push_back(tmp2);
}
sovle();
for(int i=1;i<=n;i++){
for(int j=0;j<edge[i].size();j++){
if(belong[i] == belong[edge[i][j]])
continue;
du[belong[i]]++;
}
}
int sum = 0;
int tp;
for(int i=1;i<=scc;i++){
if(!du[i]){
sum++;
tp = i;
}
}
if(sum!=1){
printf("0\n");
}
else
printf("%d\n",num[tp]);
}
return 0;
}