Hdoj1285 topological sorting
Determine competition rankings
Analysis:
Obviously, Topology Sorting is the first step. It looks simple and contains hidden weapons. During the first step, their depth is marked by topological sorting. For example, the example {1 2; 2 3; 4 3} given in the question is {1 2; 2 3; 4 3 }. The depth of 1 is 1. The depth of 2 and 4 is 2, and the depth of 3 is 3. Then, the same depth is first output in descending order of depth. Actually, this is not the case !! For example, if the edge is {5, 3; 5, 1; 5, 4; 5, 2; 3, 1; 3, 2; 6, 4;}, you 'd better draw it by yourself, better understanding !! According to my first thought, their depth ranges from 1 to 6, which are, 3, and 5, 4, 1, and 2. Actually, Li. The correct result should be 5, 3, 1, 6, 2, 4.
At first, there were no numbers greater than 5 and 6, 5 <6, so 5 was output. In this case, there is no 5. After removing 5, we find that there is no greater number than 3, and 3 is less than 6. Therefore, we first output 3. 3 is removed, and there is no larger number than 1 ............. Until all vertices are output.
The correct solution is as follows:
1) Select a point p output with an inbound degree of 0;
2) delete a pvertex.
3) convert the inbound degree of all p successor points to 1.
4) Repeat 1-3 until all vertices are output.
#include
#include
#include
#include
#includeusing namespace std;int n, m, mx, v[505], e[505][505], ru[505];void topu(){ int sum = 0; int flag = 1; while(sum < n) { for(int i = 1; i <= n; i++) { if(v[i] == 0 && ru[i] == 0) { v[i] = 1; if(flag == 1) {printf("%d", i);flag = 0;} else printf(" %d", i); for(int j = 1; j <= n; j++) { if(e[i][j] == 1) { ru[j]--; e[i][j] = 0; } } sum++; break; } } }}int main(){ while(scanf("%d%d", &n, &m) != EOF) { memset(e, 0, sizeof(e)); memset(v, 0, sizeof(v)); memset(ru, 0, sizeof(ru)); for(int i = 1; i <= m; i++) { int x, y; scanf("%d%d", &x, &y); if(e[x][y] == 0) { e[x][y] = 1; ru[y]++; } } topu(); cout << endl; } return 0;}