Harry and Magical Computer
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 73 Accepted Submission(s): 34
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
Source
BestCoder Round #25
题目大意: 哈利用一个魔法电脑处理N个任务,但是有M个前后关系(a,b),
意思是在b执行之前必须先执行a,即a任务在b任务前,问你是否能满足要求
处理完这N个任务。
思路:拓扑排序,用到了队列。先将所有入度为0的点入队,并用Count统计
入度不为0的点。遍历队列中的点所连的所有边,并减少该点连接边另一端的
入度,只要另一端入度为0了,就将它加入队列中,并统计这一端的个数id。
最后比较id和Count是否相等就可以判断是否能处理完这N个任务。
#include<iostream> #include<algorithm> #include<queue> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 110; const int MAXM = 10010; int head[MAXN],indegree[MAXM],N,M,T; struct EdgeNode { int to; int w; int next; }; EdgeNode Edges[MAXM]; int toposort() { queue<int> Q; int u; int Count = 0; for(int i = 1; i <= N; i++) { if(indegree[i] == 0) Q.push(i); else Count++; } int id = 0; while(!Q.empty()) { u = Q.front(); Q.pop(); for(int i = head[u]; i != -1; i = Edges[i].next) { indegree[Edges[i].to]--; if(indegree[Edges[i].to]==0) { id++; Q.push(Edges[i].to); } } } if(id < Count) return false; else return true; } int main() { int x,y; while(cin >> N >> M) { memset(head,-1,sizeof(head)); memset(indegree,0,sizeof(indegree)); for(int i = 0; i < M; i++) { cin >> x >> y; Edges[i].to = y; Edges[i].w = 1; Edges[i].next = head[x]; head[x] = i; indegree[y]++; } if(toposort()) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }