您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: