Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 40402 | Accepted: 16448 |
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
先缩点,如果只有一个出度为0的点,才存在符合题意的牛,数量为该强联通分量里的点
特判只有一个强联通分量的情况,直接输出n
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
const int MAXN = 10005;
const int MAXM = 50005;
const int INF = 0x3f3f3f3f;
/***************************************/
struct Edge
{
int to,Next;
}edge[MAXM];
int head[MAXN],tot;
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];
int Index,top;
int scc;
bool Instack[MAXN];
int num[MAXN];
void addedge(int u,int v)
{
edge[tot].to = v;
edge[tot].Next = head[u];
head[u] = tot++;
}
void Tarjan(int u)
{
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u]; i != -1; i = edge[i].Next) {
v = edge[i].to;
if(!DFN[v]) {
Tarjan(v);
if(Low[u] > Low[v]) Low[u] = Low[v];
}
else if(Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
if(Low[u] == DFN[u]) {
scc++;
do {
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
}
while(v != u);
}
}
void solve(int N)
{
memset(DFN,0,sizeof(DFN));
memset(Instack,false,sizeof(Instack));
memset(num,0,sizeof(num));
Index = scc = top = 0;
for(int i = 1; i <= N; i++) {
if(!DFN[i]) {
Tarjan(i);
}
}
}
int in[MAXN],out[MAXN];
void init()
{
tot = 0;
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(head,-1,sizeof(head));
}
/***************************************/
int main(void)
{
int n,m,u,v;
scanf("%d %d",&n,&m);
init();
for(int i = 1; i <= m; i++) {
scanf("%d %d",&u,&v);
addedge(u,v);
}
solve(n);
if(scc == 1) {
printf("%d\n",n);
return 0;
}
for(int i = 1; i <= n; i++) {
for(int j = head[i]; j != -1; j = edge[j].Next) {
u = Belong[i],v = Belong[edge[j].to];
if(u != v) out[u]++,in[v]++;
}
}
int cnt = 0,ans;
for(int i = 1; i <= scc; i++) {
if(out[i] == 0) {
cnt++;
ans = num[i];
}
}
if(cnt == 1) printf("%d\n",ans);
else printf("0\n");
return 0;
}