Harry and Magical ComputerTime
limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 265 Accepted Submission (s): 123
Problem DescriptionIn reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins-deal with a process, it'll 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 is some dependencies between some processes. When there exists a dependencies (a, b), it means process B must is finished before process a. By knowing all the M dependencies, Harry wants to know if the computer can finish all the n processes.
Inputthere is several test cases, you should process to the end of file.
For each test case, there is numbers N m on the first line, indicates the number processes and the number of Dependen Cies. 1≤n≤,1≤m ≤10000
The next following m lines, each line contains the numbers a B, indicates a dependencies (a, B). 1≤a,b≤n
Outputoutput 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
#include <iostream> #include <algorithm> #include <string> #include <cstdio> #include < cstring> #include <cstdlib> #include <cmath> #include <vector> #include <queue> #include < stack> #include <map> #include <set>using namespace std; #define Lson Rt<<1,l,mid#define Rson rt< <1|1,mid+1,r//#define Lson root<<1//#define Rson root<<1|1#define MID ((l+r) >>1) typedef long LONG Ll;typedef pair<int,int> p;const int maxn=10005;const int base=1000;const int Inf=999999;const double Eps=1e-5;int d[maxn];vector<int> g[maxn];bool tupo_sort (int n) {stack<int> s; for (int i=1;i<=n;i++) if (d[i]==0) s.push (i); int cnt=0; while (!s.empty ()) {int m=s.top ();//printf ("%d", m); S.pop (); cnt++; for (int i=0;i<g[m].size (); i++) {d[g[m][i]]--; if (d[g[m][i]]==0) S.push (G[m][i]); }} if (Cnt<n) return false; Return TRue;} int main () {int n,m,i,j,k,t; while (~SCANF ("%d%d", &n,&m)) {memset (d,0,sizeof (d)); for (i=0;i<=n;i++)//Per use note emptying here forgot the error many times g[i].clear (); while (m--) {int s,e; scanf ("%d%d", &s,&e); G[e].push_back (s); d[s]++; } if (Tupo_sort (n)) puts ("YES"); Else puts ("NO"); } return 0;}
Topological sequencing Hangzhou electric 5154 Harry and magical computer