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

POJ 2186 Popular Cows

2015-03-14 20:21 302 查看

Popular Cows

Time Limit: 2000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 2186

64-bit integer IO format: %lld Java class name: Main

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

解题:因为仰慕关系具有传递性,因此在一个强连通分量中的顶点:如果强连通分量中的一头牛A受到强连通分量外的另一头牛B的仰慕,则该强连通分量中的每头牛都受B仰慕。强连通缩点后,如果只有一个scc出度为0,则此scc中的点所有点的仰慕。如果多个,当然不存在任何点受其他仰慕了。因为一个scc中的点都是相互仰慕的。

#include <cstdio>
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
const int maxn = 10010;
int dfn[maxn],low[maxn],head[maxn],belong[maxn],scc,tot,idx;
int outde[maxn];
bool instack[maxn];
stack<int>stk;
struct arc{
int to,next;
arc(int x = 0,int y = -1){
to = x;
next = y;
}
}e[200000];
void add(int u,int v){
e[tot] = arc(v,head[u]);
head[u] = tot++;
}
void tarjan(int u){
dfn[u] = low[u] = idx++;
stk.push(u);
instack[u] = true;
for(int i = head[u]; ~i; i = e[i].next){
if(dfn[e[i].to] == -1){
tarjan(e[i].to);
low[u] = min(low[u],low[e[i].to]);
}else if(instack[e[i].to]) low[u] = min(low[u],dfn[e[i].to]);
}
if(dfn[u] == low[u]){
scc++;
int v;
do{
v = stk.top();
stk.pop();
instack[v] = false;
belong[v] = scc;
}while(v != u);
}
}
int main(){
int n,m,u,v;
while(~scanf("%d %d",&n,&m)){
memset(head,-1,sizeof(head));
memset(belong,0,sizeof(belong));
memset(dfn,-1,sizeof(dfn));
memset(low,-1,sizeof(low));
memset(outde,0,sizeof(outde));
while(!stk.empty()) stk.pop();
tot = scc = idx = 0;
for(int i = 0; i < m; ++i){
scanf("%d %d",&u,&v);
add(u,v);
}
for(int i = 1; i <= n; ++i)
if(dfn[i] == -1) tarjan(i);
for(int i = 1; i <= n; ++i)
for(int j = head[i]; ~j; j = e[j].next)
if(belong[i] != belong[e[j].to]) outde[belong[i]]++;
int ans = 0,p = 0;
for(int i = 1; i <= scc; ++i)
if(!outde[i]) p = i,ans++;
if(ans == 1){
ans = 0;
for(int i = 1; i <= n; ++i) if(belong[i] == p) ans++;
printf("%d\n",ans);
}else puts("0");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: