POJ-3687 Labeling Balls(拓扑)

时间:2022-08-02 04:16:36

不一样的拓扑排序 
给定一些标记为1到n的数, 求出满足a < b 的序列, 如果有多个输出, 按先标签1往前的位置, 然后按标签2往前的位置, 对于每个标签, 位置都尽量往前。 
因为位置要往前,就不能正向建图, 因为正向的拓扑每次在最前的都是最小的点, 并不能保证标签1也在最前面, 比如 
1 5 3 4 2 
和 
1 4 5 3 2 
如果按拓扑排序, 答案一定是1 4 5 3 2, 因为4比5小, 但是题目想要各个标签的位置往前, 这样1, 2标签位置一样, 对于3标签, 第一个在3处, 第二个在4处, 所以答案应该是上面那个。 
所以正向建图是标签尽量往前,所以就反向建图得到 
2 4 3 5 1 
和 
2 3 5 4 1 
用less 的优先队列, 这样每次都把最大的放在后面, 就把小的留在前面了, 对于每一个标签, 都尽可能往后扔,最后在倒叙输出, 就可以得到答案。 
题目还有一个点, 要求输出不是排序以后的各个标签的顺序, 而是在从1-n位置上的标签。 
所以在倒叙的时候需要 ans[t] = num–;

#include<map>
#include<queue>
#include<string>
#include<vector>
#include<math.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f typedef long long int ll;
using namespace std; const int maxn = ; int n, m;
int ans[maxn];
int ind[maxn];
bool maps[maxn][maxn]; void init() {
memset(ans, , sizeof ans);
memset(ind, , sizeof ind);
memset(maps, , sizeof maps);
} bool topu() {
int num = n;
priority_queue<int, vector<int>, less<int> > pq;
for(int i=; i<=n; i++) {
if(ind[i] == ) {
pq.push(i);
}
}
while(!pq.empty()) {
int t = pq.top();
pq.pop();
ans[t] = num--;
for(int i=; i<=n; i++) {
if(maps[t][i] == true) {
ind[i]--;
if(ind[i] == )
pq.push(i);
}
}
}
if(num == )
return true;
else
return false;
} int main() {
int T;
scanf("%d", &T);
while(T--) {
init();
scanf("%d%d", &n, &m);
for(int i=; i<m; i++) {
int u, v;
scanf("%d%d", &u, &v);
if(!maps[v][u]) {
maps[v][u] = true;
ind[u] ++;
}
}
bool bo = topu();
if(bo) {
for(int i=; i<=n; i++) {
printf("%d%c", ans[i], i==n ? '\n' : ' ');
}
} else {
printf("-1\n");
}
}
return ;
}