Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 28016 | Accepted: 11294 |
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.
* 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<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
typedef long long ll;
#define eps 1e-8
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hi\n")
using namespace std;
#define INF 0x3f3f3f3f
#define N 10005
int head[N],dfn[N],low[N],belong[N];
bool instack[N];
int all,Time,num;
int out[N];
int n,m;
stack<int>s;
struct stud{
int to,ne;
}e[N*5];
inline void add(int u,int v)
{
e[num].to=v;
e[num].ne=head[u];
head[u]=num++;
}
void dfs(int u,int fa)
{
// printf("%d\n",u);
dfn[u]=low[u]=++Time;
s.push(u);
instack[u]=true;
for(int i=head[u];i!=-1;i=e[i].ne)
{
int to=e[i].to;
if(dfn[to]==-1)
{
dfs(to,i);
low[u]=min(low[u],low[to]);
}
else if(instack[to])
low[u]=min(low[u],low[to]);
}
if(low[u]==dfn[u])
{
++all;
int temp;
do{
temp=s.top();
s.pop();
instack[temp]=false;
belong[temp]=all;
}while(temp!=u);
}
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));
num=0;
int u,v;
while(m--)
{
scanf("%d%d",&u,&v);
add(u,v);
}
memset(dfn,-1,sizeof(dfn));
memset(low,-1,sizeof(low));
memset(instack,false,sizeof(instack));
while(!s.empty()) s.pop();
all=0;
Time=0;
// bug;
for(i=1;i<=n;i++)
if(dfn[i]==-1)
dfs(i,-1);
// bug;
memset(out,0,sizeof(out));
for(i=1;i<=n;i++)
for(j=head[i];j!=-1;j=e[j].ne)
{
int to=e[j].to;
if(belong[i]==belong[to]) continue;
out[belong[i]]++;
}
int cnt=0,last;
for(i=1;i<=all;i++)
if(out[i]==0)
{
cnt++;
last=i;
}
if(cnt!=1)
{
printf("0\n");
continue;
}
int ans=0;
for(i=1;i<=n;i++)
if(belong[i]==last) ans++;
printf("%d\n",ans);
}
return 0;
}