POJ 2186 Popular Cows
2017-10-15 13:49
330 查看
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 |
现在问有多少头牛是会被其他牛都仰慕。
思路:仰慕关系具有传递性,那么可以关系成环。可以用tarjan求缩点,然后看看有多少个环,只有一个环时成立,有多个环就不可能被所有牛仰慕,
#include<stack> #include<cstdio> #include<iostream> #define MAXN 10001 #define MAXM 50001 using namespace std; struct node { int to; int next; }; node e[MAXM+10]; int dfn[MAXN],low[MAXN],tot,head[MAXM+10]; int n,m,sum; int out[MAXN],f[MAXN]; bool vis[MAXN]; stack<int> s; inline void read(int&x) { x=0;int f=1;char c=getchar(); while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(x<<1)+(x<<3)+c-48;c=getchar();} x=x*f; } inline void add(int x,int y) { e[++tot].to=y; e[tot].next=head[x]; head[x]=tot; } inline void tarjan(int u) { dfn[u]=low[u]=++tot; vis[u]=true; s.push(u); for(int i=head[u];i;i=e[i].next) { int v=e[i].to; if(!dfn[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(vis[v]) low[u]=min(low[u],dfn[v]); } if(dfn[u]==low[u]) { ++sum; int t; do { t=s.top(); s.pop(); vis[t]=false; f[t]=sum; }while(u!=t); } } int main() { int x,y; read(n);read(m); for(int i=1;i<=m;i++) { read(x);read(y); add(x,y); } tot=0; for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i); for(int i=1;i<=n;i++) for(int j=head[i];j;j=e[j].next) { int v=e[j].to; if(f[i]!=f[v]) { out[f[i]]++; } } int ouy=0,k; for(int i=1;i<=sum;i++) if(!out[i]) { ouy++; k=i; } if(ouy>1) printf("0\n"); else { int ans=0; for(int i=1;i<=n;i++) if(f[i]==k) ans++; printf("%d\n",ans); } return 0; }
View Code
相关文章推荐
- poj 2186 Popular Cows
- POJ 2186 Popular Cows(缩点+出度判断)
- poj 2186 Popular Cows 缩点
- POJ 2186 Popular Cows 强连通分量 kosaraju
- POJ 2186 Popular Cows(强联通分量)
- poj 2186 Popular Cows (强连通分量,缩点)
- POJ 2186 Popular Cows (强联通)
- POJ 2186 Popular Cows(强连通分量缩点)
- POJ-2186 Popular Cows (强连通缩点)
- poj 2186 Popular Cows Tarjan 强连通分量
- 有向图的汇点 -- 兼 ACM PKU POJ 2186 ( Popular Cows ) 解题报告
- POJ 2186-Popular Cows
- 【Kosaraju && 连通分量】POJ - 2186 Popular Cows
- poj 2186 Popular Cows (tarjan + 缩点)
- POJ 2186 Popular Cows
- Popular Cows POJ - 2186 找金字塔顶点?
- poj 2186——Popular Cows
- Poj 2186 Popular Cows
- poj2186 Popular Cows(强连通缩点)
- poj 2186 Popular Cows 强连通缩点