POJ 3687 Topo 拓扑

来源:互联网 发布:广州数控车床编程软件 编辑:程序博客网 时间:2024/04/30 11:34
#include <iostream>#include <vector>#include <queue>const int MAXN = 205;int N, M;int out[MAXN];int adjMat[MAXN][MAXN];std::vector<int> ans[MAXN];int res[MAXN];int ball[MAXN];void topo(){int idx = 1;std::priority_queue<int, std::vector<int>, std::less<int>> q;for(int i = 1; i <= N; i++){if(out[i] == 0)q.push(i);}while(!q.empty()){int first = q.top();res[idx++] = first;q.pop();int size = ans[first].size();for(int i = 0; i < size; i++){out[ans[first][i]]--;if(out[ans[first][i]] == 0)q.push(ans[first][i]);}}idx--;if(idx == N){for(int i = 1; i <= N; i++){ball[res[i]] = N - i + 1;}for(int i = 1; i <= N - 1; i++){printf("%d ", ball[i]);}printf("%d\n", ball[N]);}else{printf("-1\n");}}bool findLoop(){int k, i, j;for(k = 1; k <= N; k++)for(i = 1; i <= N; i++)for(j = 1; j <= N; j++){if(adjMat[i][k] == 1 && adjMat[k][j] == 1)adjMat[i][j] = 1;}for(i = 1; i <= N; i++){if(adjMat[i][i] == 1){return true;}}return false;}void run(){memset(adjMat, 0, sizeof(adjMat));memset(out, 0, sizeof(out));memset(res, 0, sizeof(res));memset(ball, 0, sizeof(ball));for(int i = 1; i <= N; i++)ans[i].clear();bool ok = true;int x, y;for(int i = 1; i <= M; i++){scanf("%d%d", &x, &y);adjMat[x][y] = 1;if(x == y){ok = false;}else{out[x]++;ans[y].push_back(x);}}if(!ok){printf("-1\n");}else{if(findLoop()){printf("-1\n");}else{topo();}}}int main(){int caseCnt;scanf("%d", &caseCnt);while(caseCnt--){scanf("%d%d", &N, &M);run();}return 0;}