1.链接地址

https://vjudge.net/problem/POJ-3687

2.问题描述

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?

输入样例

5

4 0

4 1
1 1

4 2
1 2
2 1

4 1
2 1

4 1
3 2

输出样例

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

3.解题思路

比较简单的拓扑题目

给定一些类似a<b的约束,表示编号为a的球比编号为b的球轻。要求符合约束条件的各个球的重量。若答案有多种,则输出的答案必须让编号为1的球重量尽量轻,接着是编号为2的球重量尽量轻,一直到编号为N的球尽量轻。

输出输出的是球1到球N的重量,

4.算法实现源代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<cmath>
using namespace std;

const int maxn=200+10;

int in[maxn],map[maxn][maxn],ans[maxn],flag;

void topsort(int n)
{
    int k=n,i;
    while(k>=1)
    {
        for(i=n;i>=1;i--)
        {
            if(in[i]==0)
            {
                for(int j=1;j<=n;j++)
                {
                    if(map[i][j]==1)
                    {
                        in[j]--;
                    }
                }
                in[i]--;
                ans[i]=k--;
                break;
            }
        }
        if(i==0)
        {
            flag=0;
            break;
        }
    }
}

int main()
{
    int t,n,m,a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        memset(in,0,sizeof(in));
        memset(map,0,sizeof(map));
        flag=1;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&a,&b);
            if(a!=b)
            {
                if(map[b][a]==0)
                {
                    map[b][a]=1;
                    in[a]++;
                }
            }
            else
            {
                flag=0;
            }
        }
        
        if(flag)
        {
            topsort(n);
            if(flag==0)
            {
                cout<<"-1"<<endl;
                continue;
            }
            for(int i=1;i<=n;i++)
            {
                cout<<ans[i]<<" ";
            }
            cout<<endl;
        }
        else
        {
            cout<<"-1"<<endl;
        }
    }
}