您的位置:首页 > 其它

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

2016-07-15 16:33 363 查看


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. 1≤n≤100,1≤m≤10000

The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1≤a,b≤n

 

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

 

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

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

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define N 1000
int d
,vis
;
struct Edge
{
int u,v,next;
} edge[N*10];
int cnt,head
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: