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

poj2186 Popular Cows(强连通缩点)

2015-11-22 21:11 405 查看
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.

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

#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
,dfn
,low
,belong
;
bool instack
;
int all,Time,num;
int out
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: