POJ3687 Labeling Balls(反向拓扑)

前言:第一道拓扑排序题。。。

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:
No two balls share the same label. 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

题目要求尽可能编号越大,重量越大,那么反向建边,利用拓扑排序,从编号大的开始搜,当找到入度为0的点时,给这个点赋值,然后break,若没有入度为0的点,说明有环,那么不满足题目要求,输出-1。
代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
using namespace std;
typedef long long  ll;
const int MAXN=1e4+5;
const int mod=1e9+7;
const int INF =0x3f3f3f;
int e[205][205];
int ans[205];
int in[205];
int n,m;
int toposort()
{
    
    
    int w,i;
    for( w=n;w>=1;w--)
    {
    
    
        for( i=n;i>=1;i--)
        {
    
    
            if(in[i]==0)
            {
    
    
                in[i]--;
                ans[i]=w;
                for(int j=1;j<=n;j++)
                {
    
    
                    if(e[i][j]==1) in[j]--;
                }
                break;
            }
        }
        if(i==0) break;
    }
    if(w!=0) return -1;
    else return 1;
}
int main()
{
    
    
    int t;
    cin>>t;
    while(t--)
    {
    
    
        memset(e,0,sizeof e);
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        {
    
    
            in[i]=0;
            ans[i]=0;
        }
        int a,b;
        for(int i=1;i<=m;i++)
        {
    
    
            cin>>a>>b;
            if(e[b][a]==0)
            {
    
    
                e[b][a]=1;
                in[a]++;
            }
        }
        if(toposort()==1)
        {
    
    
            for(int i=1;i<=n;i++)
            {
    
    
                cout<<ans[i]<<" ";
            }
            cout<<endl;
        }
        else
        {
    
    
            cout<<-1<<endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45755679/article/details/107401473