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
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).
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
思路:跑一遍拓扑排序,看是否能遍历到所有的点即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define N 1000
int 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;
}
本文介绍了一个关于魔法计算机处理任务的问题,计算机需要处理一系列任务,并且这些任务之间存在依赖关系。文章通过拓扑排序的方法判断了计算机是否能够顺利完成所有任务。
919

被折叠的 条评论
为什么被折叠?



