fork download
  1. #include<iostream>
  2. #include<cstring>
  3. #include<map>
  4. #include<stack>
  5. #include<algorithm>
  6. #define MAX 10000000;
  7. using namespace std;
  8.  
  9. int main(){
  10.  
  11.  
  12. long long int test_case,w=1;
  13. cin>>test_case;
  14. int winner[10],infcount=0;
  15. while(w<=test_case){
  16.  
  17. long long int n,d; // process (1 to n), dependencies
  18. cin>>n>>d;
  19. bool matrix[n+1][n+1];
  20. memset(matrix,0,sizeof(matrix));
  21. long long int i;
  22.  
  23. for(i=1;i<=d;i++){
  24. long long int process,dependency;
  25. cin>>process>>dependency;
  26. matrix[process][dependency] = 1;
  27. }
  28. map<long long int,long long int> degree;
  29. for(i=1;i<=n;i++){
  30. long long int count = 0;
  31. for(long long int j=1;j<=n;j++){
  32. if(matrix[j][i]==1)
  33. count++;
  34. }
  35. degree[i] = count;
  36. }
  37. long long int result = 0;
  38. while(!degree.empty()){
  39. map<long long int,long long int>::iterator it = degree.begin() , end = degree.end() , temp;
  40. bool flag = 0;
  41. stack< map<long long int,long long int>::iterator > st;
  42. while(it!=end){
  43. if(it->second == 0){
  44. st.push(it);
  45. flag = 1;
  46. }
  47. it++;
  48. }
  49. while(!st.empty()){
  50. temp = st.top();
  51. st.pop();
  52. long long int index = temp->first;
  53. // cout<<index<<" ";
  54. degree.erase(temp);
  55. for(long long int j = 1;j<=n;j++){
  56. if(matrix[index][j]==1){
  57. matrix[index][j] = 0;
  58. degree[j]--;
  59. }
  60. }
  61. }
  62. if(flag==0)
  63. break;
  64. result++;
  65. }
  66. if(!degree.empty()){
  67. infcount++;
  68. winner[w]=MAX;
  69.  
  70. }
  71. else{
  72. winner[w]=result;
  73.  
  74. }
  75. w++;
  76. }
  77. int min=MAX;int flag=0,team;
  78.  
  79. if(infcount==test_case)
  80. cout<<"0";
  81. else{
  82.  
  83. for(int i=1;i<=test_case;i++){
  84. if(winner[i]<min){
  85. min=winner[i];
  86. team=i;
  87. }
  88. }
  89.  
  90. for(int i=1;i<=test_case;i++)
  91. if(winner[i]==min)
  92. flag++;
  93.  
  94. if(flag>=2)
  95. cout<<"0";
  96. else
  97. cout<<team;
  98. }
  99.  
  100.  
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 3476KB
stdin
6
40 50
37 1
15 3
5 4
18 5
23 6
26 7
20 8
37 9
21 10
34 11
32 12
24 13
1 14
12 15
35 16
37 17
15 18
12 19
32 20
24 21
14 22
2 23
1 24
30 25
31 26
26 27
23 28
19 29
32 30
32 31
2 32
31 33
20 34
37 35
10 36
2 37
15 38
29 39
29 40
8 10
24 2
13 22
11 26
21 19
33 37
31 8
32 21
9 8
34 40
17 39
12 24
11 1
4 2
8 3
11 4
4 5
10 6
11 7
11 8
4 9
7 10
7 12
1 4
3 9
5 6
1 7
5 2
7 4
9 2
1 9
4 8
8 6
4 10
6 11
4 6
4 6
2 1
3 2
3 4
4 1
2 4
1 3
3 6
1 2
3 1
3 2
2 1
1 3
1 2
6 30
1 2
1 3
1 4
1 5
1 6
2 1
2 3
2 4
2 5
2 6
3 2
3 1
3 4
3 5
3 6
4 2
4 3
4 1
4 5
4 6
5 2
5 3
5 4
5 1
5 6
6 2
6 3
6 4
6 5
6 1
4 2
1 2
2 1
5 8
1 2
1 3
1 4
1 5
5 4
2 5
2 1
3 5
stdout
Standard output is empty