POJ 3687 Labeling Balls (top 排序)

                         Labeling Balls
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 15792   Accepted: 4630

Description

Windy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 to N in such a way that:

  1. No two balls share the same label.
  2. The labeling satisfies several constrains like "The ball labeled with a is lighter than the one labeled with b".

Can you help windy to find a solution?

Input

The first line of input is the number of test case. The first line of each test case contains two integers, N (1 ≤ N ≤ 200) and M (0 ≤ M ≤ 40,000). The next M line each contain two integers a and b indicating the ball labeled with a must be lighter than the one labeled with b. (1 ≤ a, b ≤ N) There is a blank line before each test case.

Output

For each test case output on a single line the balls' weights from label 1 to label N. If several solutions exist, you should output the one with the smallest weight for label 1, then with the smallest weight for label 2, then with the smallest weight for label 3 and so on... If no solution exists, output -1 instead.

Sample Input

5

4 0

4 1
1 1

4 2
1 2
2 1

4 1
2 1

4 1
3 2

Sample Output

1 2 3 4
-1
-1
2 1 3 4
1 3 2 4

思路:
这题是很明显的top排序,只是这个排序有一点技巧。
那就是逆序排序,为什么要这么做?
我们知道,top排序删掉一个点,那么就会解锁后面的某些点,虽然正向操作,可以让当前的数字最小,但是不一定让后面解锁的更优。此时你要时刻记得,入队的顺序,并不是你输出的顺序。
而如果采用逆序的话,小的元素一定可以留到最后,再进行标号(当然标号也要大到小呀)。毕竟让字典序最小,是从小的元素开始算起的。
代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
vector<int>u[208];
int n,m,num;
int ss[208];
int in[208];
void init()
{
    memset(in,0,sizeof(in));
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        u[i].clear();
    }
    int x,y;
    for(int i=1;i<=m;i++){
        scanf("%d%d",&x,&y);
        u[y].push_back(x);
        in[x]++;
    }
}

void Top_sort()
{
    priority_queue<int> q;
    queue<int>ans;
    for(int i=1;i<=n;i++){
        if(in[i]==0){q.push(i);}
    }
    int t;
    while(!q.empty()){
        t=q.top();q.pop();
        ans.push(t);
        int siz=u[t].size();
        for(int i=0;i<siz;i++){
            in[u[t][i]]--;
            if(in[u[t][i]]==0){
                q.push(u[t][i]);
            }
        }
    }
    int num=n;
    if(ans.size()!=n){printf("-1\n");return;}
    else{
        while(!ans.empty()){
            t=ans.front();ans.pop();
            ss[t]=num--;
        }

        printf("%d",ss[1]);
        for(int i=2;i<=n;i++){
            printf(" %d",ss[i]);
        }
        printf("\n");
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        init();
        Top_sort();
    }
}

  

猜你喜欢

转载自www.cnblogs.com/ZGQblogs/p/9396475.html