您的位置:首页 > 运维架构

POJ2186 Popular Cows 强连通分量

2016-08-12 15:27 323 查看
Popular Cows

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 30459 Accepted: 12365
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
题意:有n头牛,每头牛都有一个自己崇拜的牛,当A崇拜B且B崇拜C是那么A也崇拜C,先给出崇拜关系,问你有多少其他所有牛都崇拜的牛。
思路:在一个强连通分量内,任意一头牛一定会被该分量其他牛所崇拜,因此先求出所有的强连通分量,然后对其进行缩点并求出所有点的出度,当只有一个出度为0是,该分量内的牛的数量,否则输出0。
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<vector>
using namespace std;
const int maxm=10006;
int vis[maxm]={0},num[maxm]={0},dfn[maxm]={0},low[maxm]={0},p[maxm],belong[maxm]={0},sum=1,id=1;
int g[maxm]={0},f[maxm]={0};
vector<int>v[maxm];
stack<int>s;
typedef struct
{
int x,y;
}H;
H a[maxm];
void tarjian(int x);
int find(int k);
int main()
{
int i,j,k,n,m,x,y;
memset(p,-1,sizeof(p));
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
v[x].push_back(y);
}
for(i=1;i<=n;i++)
{
if(!dfn[i])
tarjian(i);
}
for(i=1;i<=n;i++)
{
for(j=0;j<v[i].size();j++)
{
int xx=v[i][j];
if(belong[xx]!=belong[i])
g[belong[i]]+=1;
}
}
int d,ans=0;
for(i=1;i<sum;i++)
{
if(g[i]==0)
{
d=num[i];
ans++;
}
if(ans>1)
break;
}
if(ans==1)
printf("%d\n",d);
else
printf("0\n");
return 0;
}
void tarjian(int x)
{
int i,j;
s.push(x);vis[x]=1;low[x]=dfn[x]=id++;
for(j=0;j<v[x].size();j++)
{
int xx=v[x][j];
if(!dfn[xx])
{
tarjian(xx);
low[x]=min(low[x],low[xx]);
}
else if(vis[xx])
low[x]=min(low[x],dfn[xx]);
}
if(dfn[x]==low[x])
{
while(s.size())
{
int xx=s.top();s.pop();
num[sum]++;
vis[xx]=0;
belong[xx]=sum;
if(xx==x)
break;
}
sum++;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: