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;
}
相关文章推荐
- php set get asset unset
- php set get asset unset
- AOP的使用
- POJ 1200
- mysql 5.6 binlog组提交
- DI中Transient Scoped Singleton Instance的区别
- perl 处理文本
- perl 处理文本
- String equals的技巧
- 弱占优策略--Weakly Dominant Strategy
- Java_JVM_逃逸分析技术_栈上分配_标量替换
- 树(1)把二叉查找树转换成有序的双向链表
- Identity Mappings in Deep Residual Networks
- How to enter an End-Of-File from the keyboard
- Jedis使用总结
- Oracle 正常关闭后 startup mount 提示监听程序当前无法识别连接描述附中请求的服务
- 502款开源iOS应用的开源项目
- 关于platform_led驱动的问题
- UE4 return value 获得单个值
- 跟着官网的例子学Reacjs (一)FilterableProductTable