hdu 5154(拓扑排序)

Harry and Magical Computer

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2017    Accepted Submission(s): 801


Problem Description
In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins to deal with a process, it will work until the ending of the processes. One day the computer got n processes to deal with. We number the processes from 1 to n. However there are some dependencies between some processes. When there exists a dependencies (a, b), it means process b must be finished before process a. By knowing all the m dependencies, Harry wants to know if the computer can finish all the n processes.
 

 

Input
There are several test cases, you should process to the end of file.
For each test case, there are two numbers n m on the first line, indicates the number processes and the number of dependencies. 1n100,1m10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1a,bn
 

 

Output
Output one line for each test case.
If the computer can finish all the process print "YES" (Without quotes).
Else print "NO" (Without quotes).
 

 

Sample Input
3 2 3 1 2 1 3 3 3 2 2 1 1 3
 

 

Sample Output
YES NO
 
题意:有n个进程,n个进程有m条联系,如果(a,b)那么代表b要在a之前完成,现有m条联系,问所有的进程能否都完成??
题解:这个题开始想简单了,以为只要判环就行了,用并查集去做果然WA,然后发现这是有向边,所以我们可以采用拓扑排序,看最后拓扑排序进入队列的点是否为n,如果是,那么都可以完成,如果不是,那么就有一些陷入了死循环。
给一组数据:
3 3
3 1
2 1
3 2
ans:YES
#include<stdio.h>
#include<iostream>
#include<string.h>
#include <stdlib.h>
#include<math.h>
#include<algorithm>
#include <queue>
using namespace std;
int indegree[105];
struct Edge{
    int v,next;
}edge[10005];
int head[105];
int tot;
void addEdge(int u,int v,int &k){
    edge[k].v = v,edge[k].next = head[u],head[u] = k++;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        memset(indegree,0,sizeof(indegree));
        memset(head,-1,sizeof(head));
        tot=0;
        for(int i=1;i<=m;i++){
            int u,v;
            scanf("%d%d",&u,&v);
            addEdge(v,u,tot);
            indegree[u]++;
        }
        queue<int >q;
        for(int i=1;i<=n;i++){
            if(indegree[i]==0) q.push(i);
        }
        int cnt = 0;
        while(!q.empty()){
            int u = q.front();
            cnt++;
            q.pop();
            for(int k=head[u];k!=-1;k=edge[k].next){
                indegree[edge[k].v]--;
                if(!indegree[edge[k].v]) q.push(edge[k].v);
            }
        }
        if(cnt==n) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}
/**
3 3
3 1
2 1
3 2
*/

 

posted @ 2016-07-15 11:16  樱花庄的龙之介大人  阅读(210)  评论(0编辑  收藏  举报