HDU 1285 - 确定比赛名次 <拓扑排序>
这题本来想按照算法竞赛入门经典上的DFS来做,但是无奈这个题有点特殊,有重边的情况,所以学习了另外一种复杂度相同切更好理解的一种算法。
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #define maxn 512 using namespace std; int n, m, cnt; bool G[maxn][maxn], vis[maxn]; int res[maxn], in[maxn]; int main() { ios::sync_with_stdio(false); while(memset(G, false, sizeof(G)), memset(vis, false, sizeof(vis)), memset(in, 0, sizeof(in)), cnt = 1, cin >> n >> m){ for(int i = 0; i < m; ++i){ int x, y; cin >> x >> y; if(!G[x][y]) G[x][y] = true, in[y]++; } while(cnt <= n) for(int i = 1; i <= n; ++i) if(!vis[i] && !in[i]){ vis[i] = true; res[cnt++] = i; for(int j = 1; j <= n; ++j) if(G[i][j]) in[j]--; break; } printf("%d", res[1]); for(int i = 2; i <= n; ++i) printf(" %d", res[i]); printf("\n"); } return 0; }