POJ

来源:互联网 发布:js实现select联动 编辑:程序博客网 时间:2024/06/06 17:42

上题:

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
Hint
Cow 3 is the only cow of high popularity. 
题意:
题目的意思是:
现在有很多头牛,他们想知道这群牛中最受欢迎的(所有的牛都认为他受欢迎)牛有几头,其中 ,如果a认为b受欢迎,b认为c受欢迎,那么a就认为c受欢迎。
思路:
我们现在要求出的是 这样的一群牛,它们被其他所有牛都受欢迎,换句话说 就是是,所有的牛的直接或者间接的指向他,看到这里可能会有人想到,那我们直接看,如果这群牛中 ,有且只有一个出度为0,那么在一个图中,所有点肯定都指向它,如果这样想就很接近答案了,但是我们这里所求的是一群牛,他们可能是这样的:1->2,2->3.3->1,2->4,4->5,5->6,6->4,把图画出来可以看出,他们这里没有一个点的出度是0,可以看出 ,他们这是一个环,我们把由1,2,3号点组成的环称为1环,4,5,6点组成的环称为2环,这样我们就可以看出,1环认为2环受欢迎对吧,看到这里大家就应该想到了,我们要用缩点来写了,
那么我们应该怎样写呢?这里引入了强连通分量这个词,什么是强连通,就是在一个有向图中 ,他们每个节点都是直接或者间接的相互连通的,那么我们就可以吧强连通分量里的点都当成一个点来求了之后就简单了,关于强连通分量的求法,感觉自己以后深入理解之后会出博客吧 ,现在上代码吧:
#include<stdio.h>#include<string.h>#include<algorithm>#include<stack>using namespace std;const int maxn=100000;int head[maxn],instack[maxn],low[maxn],dfn[maxn],cnt,scc,index;int belong[maxn],num[maxn],out[maxn];struct node{int to,next;}edg[maxn];void add(int u,int v){edg[cnt].to=v;edg[cnt].next=head[u];head[u]=cnt++;}stack<int>que;void dfs(int u){low[u]=dfn[u]=index++;instack[u]=1;que.push(u);for(int i=head[u];i!=-1;i=edg[i].next){int v=edg[i].to;if(!dfn[v]){dfs(v);low[u]=min(low[u],low[v]);}else if(instack){low[u]=min(low[u],dfn[v]);}}if(dfn[u]==low[u])//将连通分量中的点求出,缩点 {scc++;int v;do{v=que.top();que.pop();belong[v]=scc;num[scc]++;//各联通分量中存储的 点的个数/ }while(v!=u);}}int main(){int n,m;while(scanf("%d%d",&n,&m)!=EOF){cnt=0;scc=0;index=1;int a,b;memset(head,-1,sizeof(head));memset(dfn,0,sizeof(dfn));memset(out,0,sizeof(out));memset(instack,0,sizeof(instack));for(int i=0;i<m;i++){scanf("%d%d",&a,&b);add(a,b);}for(int i=1;i<=n;i++){if(!dfn[i]){dfs(i);}}for(int i=1;i<=n;i++){if(!out[belong[i]]){for(int j=head[i];j!=-1;j=edg[j].next){int v=edg[j].to;if(belong[i]==belong[v]){continue;}out[belong[i]]=1;//out数组记录的就是 点的出度,有链式前向星可以得出, i表示一条边的起点,v表示的是一条边的终点,由此可知,这里的out数组记录的是//belong这个点的出度。 break;}}}int ans=0;int u=0;for(int i=1;i<=scc;i++){if(!out[i]){ans++;//记录这个点的出度,如果大于一,那就证明 不可能出现所有牛的认为一群牛比他们受欢迎 u=i;if(ans>1){break;}}}//printf("u=%d\n",u);/*for(int i=1;i<=scc;i++){printf("num[%d]=%d\n",i,num[i]);}*/if(ans==1){printf("%d",num[u]);}else{printf("0\n");}}} 




原创粉丝点击