Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24039 | Accepted: 9865 |
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.
题解:若a认为b受欢迎,则建一条边a->b。将图中的强连通分量缩点以后,图一定是个DAG,所以若此时出度为0的点只有一个,那么该点所表示的强连通分量的点则为答案。
代码如下:
#include<stdio.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<stack>
#include<math.h>
#include<vector>
#include<string.h>
#define nn 11000
#define inff 0x3fffffff
using namespace std;
int n,m;
struct node
{
int en,next;
}E[nn*nn];
int p[nn],num;
void init()
{
memset(p,-1,sizeof(p));
num=0;
}
void add(int st,int en)
{
E[num].en=en;
E[num].next=p[st];
p[st]=num++;
}
int dfn[nn],low[nn],df;
int cnt;
int fa[nn];
bool insta[nn];
stack<int>sta;
void dfs(int id)
{
dfn[id]=low[id]=++df;
sta.push(id);
insta[id]=true;
int i,w;
for(i=p[id];i+1;i=E[i].next)
{
w=E[i].en;
if(dfn[w]==-1)
{
dfs(w);
low[id]=min(low[id],low[w]);
}
else if(insta[w])
low[id]=min(low[id],dfn[w]);
}
if(low[id]==dfn[id])
{
++cnt;
int ix;
while(1)
{
ix=sta.top();
sta.pop();
insta[ix]=false;
fa[ix]=cnt;
if(ix==id)
break;
}
}
}
int cd[nn];
vector<int>ans;
void solve()
{
memset(cd,0,sizeof(cd));
memset(insta,false,sizeof(insta));
memset(dfn,-1,sizeof(dfn));
df=cnt=0;
int i,j,w;
for(i=1;i<=n;i++)
{
if(dfn[i]==-1)
{
dfs(i);
}
}
for(i=1;i<=n;i++)
{
for(j=p[i];j+1;j=E[j].next)
{
w=E[j].en;
if(fa[i]!=fa[w])
{
cd[fa[i]]++;
}
}
}
int ix=0;
for(i=1;i<=cnt;i++)
{
if(cd[i]==0)
{
ix++;
for(j=1;j<=n;j++)
{
if(fa[j]==i)
{
ans.push_back(j);
}
}
}
}
if(ix==1)
printf("%d\n",ans.size());
else
puts("0");
}
int main()
{
int i;
while(scanf("%d%d",&n,&m)!=EOF)
{
int u,v;
init();
for(i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
}
ans.clear();
solve();
}
return 0;
}