poj 3687 Labeling Balls 拓扑排序
2012-04-11 15:23
411 查看
//很巧妙的反向建图,先放最重的编号最大的可使字典序最小,用优先队列实现,贪心思想。
//拓扑排序需要特别注意重边!
//拓扑排序需要特别注意重边!
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; int n, m, cnt[205], a[205][205], seq[205]; bool topo_sort(){ int i, j, t; priority_queue<int> s; for(i=1; i<=n; i++) if(cnt[i]==0){ s.push(i); } for(i=1; i<=n; i++){ if(s.empty())return false; t=s.top(); s.pop(); seq[t]=n-i+1; for(j=1; j<=n; j++){ if(a[t][j]&&(--cnt[j])==0) s.push(j); } } return true; } int main(){ //freopen("1.txt", "r", stdin); int i, j, x, T, y; scanf("%d", &T); while(T--){ scanf("%d%d", &n, &m); memset(a, 0, sizeof(a)); memset(cnt, 0, sizeof(cnt)); for(i=1; i<=m; i++){ scanf("%d%d", &x, &y); if(a[y][x])continue; a[y][x]=1; cnt[x]++; } if(topo_sort()){ printf("%d", seq[1]); for(j=2; j<=n; j++) printf(" %d", seq[j]); printf("\n"); } else printf("-1\n"); } return 0; }
相关文章推荐
- Labeling Balls(POJ 3687-逆序拓扑排序)
- POJ 3687 Labeling Balls 拓扑排序
- poj3687——Labeling Balls(拓扑排序)
- [ACM] POJ 3687 Labeling Balls (拓扑排序,逆向建边)
- POJ 3687 Labeling Balls (逆向拓扑排序)
- POJ训练计划3687_Labeling Balls(拓扑排序)
- [ACM] POJ 3687 Labeling Balls (拓扑排序,逆向建边)
- poj 3687 Labeling Balls 【拓扑排序】
- Poj 3687 Labeling Balls[拓扑排序]
- poj 3687 Labeling Balls(拓扑排序)
- POJ 3687 Labeling Balls 拓扑排序
- poj 3687 Labeling Balls 【拓扑排序】
- POJ 3687 Labeling Balls 拓扑排序
- [POJ 3687] Labeling Balls [拓扑排序]
- poj 3687 Labeling Balls(拓扑排序)
- poj 3687 Labeling Balls - 贪心 - 拓扑排序
- POJ - 3687 Labeling Balls (拓扑排序)
- POJ3687——Labeling Balls(反向建图+拓扑排序)
- poj 3687 Labeling Balls 拓扑排序
- poj 3687 Labeling Balls(拓扑排序)