hdu 5154 Harry and Magical Computer(拓扑排序)

来源:互联网 发布:数据库订单管理模板 编辑:程序博客网 时间:2024/05/17 17:56

Harry and Magical Computer

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


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 23 12 13 33 22 11 3
 

Sample Output
YESNO
 

题意:计算机有很多个任务,任务之间有依赖关系,即完成a任务必须先完成b任务,问你计算机能否完成全部的任务

思路:跑一遍拓扑排序,看是否能遍历到所有的点即可。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <queue>using namespace std;#define N 1000int d[N],vis[N];struct Edge{    int u,v,next;} edge[N*10];int cnt,head[N];void addedge(int u,int v){    edge[cnt].u=u;    edge[cnt].v=v;    edge[cnt].next=head[u];    head[u]=cnt++;}void init(){    cnt=0;    memset(head,-1,sizeof(head));    memset(d,0,sizeof(d));    memset(vis,0,sizeof(vis));}int main(){    int n,m;    int u,v;    while(~scanf("%d %d",&n,&m))    {        init();        priority_queue<int> q;        for(int i=0; i<m; i++)        {            scanf("%d %d",&u,&v);            d[u]++;            addedge(v,u);        }        for(int i=1; i<=n; i++)            if(!d[i])            {                q.push(i);                vis[i]=1;            }        while(!q.empty())        {            int u=q.top();            q.pop();            for(int i=head[u]; i!=-1; i=edge[i].next)            {                int v=edge[i].v;                d[v]--;                if(!d[v])                    {                        q.push(v);                        vis[v]=1;                    }            }        }        int flag=0;        for(int i=1; i<=n; i++)                if(!vis[i])                flag=1;        if(flag) printf("NO\n");        else printf("YES\n");    }    return 0;}




0 0
原创粉丝点击