POJ 2186 Popular Cows

来源:互联网 发布:ubuntu 安装php7 编辑:程序博客网 时间:2024/06/06 03:12
POJ 2186
Popular Cows
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 24076 Accepted: 9879

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 31 22 12 3

Sample Output

1
题意:

有N只奶牛,其中奶牛A认为奶牛B备受注目,而奶牛B也可能认为奶牛C备受注目。奶牛们的这种“认为”是单向可传递的,就是说若奶牛A认为奶牛B备受注目,但奶牛B不一定会认为奶牛A备受注目。而当A认为B备受注目,且B认为C备受注目时,A一定也认为C备受注目。

       现在给出M对这样的“认为...备受注目”的关系对,问有多少只奶牛被除其本身以外的所有奶牛关注。

算法:假设有两头牛A和B都被其它牛认为是红人。那么显然,A被B认为是红人,B也被A认为是红人,即存在一个包含A、B两个顶点的圈,或者说,A、B同属于一个强连通分量。反之、如果一头牛被其它所有牛认为是红人,那么其所属的强连通分量内的所有牛都被所有其它的牛认为是红人。由此,我们把图进行强连通分量分解后,至多有一个强连通分量满足条件。而且算法分解强连通分量的同时也记录了每个分量的拓扑排序,显然,唯一可能成为解得只可能是拓扑序最后的强连通分量。所以在最后,我们只要检查这个强连通分量是否从其它所有顶点可达就可以了。

下面是AC代码

#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<iostream>#include<algorithm>#include<sstream>#include<vector>#include<map>#include<stack>#include<list>#include<set>#include<queue>#define LL long long#define lson l,m,rt<<1#define rson m+1,r,rt<<1 | 1using namespace std;const int maxn=100005;int n,m,V,A[maxn],B[maxn];vector<int>G[maxn],RG[maxn],vs;bool vis[maxn];int cmp[maxn];void add(int from,int to){    G[from].push_back(to);    RG[to].push_back(from);}void dfs(int v){    vis[v]=1;    for(int i=0;i<G[v].size();i++)        if(!vis[G[v][i]]) dfs(G[v][i]);    vs.push_back(v);}void rdfs(int v,int k){    vis[v]=1;    cmp[v]=k;    for(int i=0;i<RG[v].size();i++)        if(!vis[RG[v][i]]) rdfs(RG[v][i],k);}int scc(){    memset(vis,0,sizeof(vis));    vs.clear();    for(int i=0;i<V;i++)        if(!vis[i]) dfs(i);    memset(vis,0,sizeof(vis));    int k=0;    for(int i=vs.size()-1;i>=0;i--)        if(!vis[vs[i]]) rdfs(vs[i],k++);    return k;}void solve(){    V=n;    for(int i=0;i<m;i++) add(A[i]-1,B[i]-1);    int s=scc();    int u=0,num=0;    for(int i=0;i<V;i++)        if(cmp[i]==s-1) u=i,num++;    memset(vis,0,sizeof(vis));    rdfs(u,0);    for(int i=0;i<V;i++)    if(!vis[i]) {num=0;break;}    printf("%d\n",num);}int main(){    while(~scanf("%d%d",&n,&m))    {        for(int i=0;i<m;i++) scanf("%d%d",&A[i],&B[i]);        solve();    }    return 0;}


0 0
原创粉丝点击