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?
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.
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.
5 4 0 4 1 1 1 4 2 1 2 2 1 4 1 2 1 4 1 3 2Sample Output
1 2 3 4 -1 -1 2 1 3 4 1 3 2 4
题目意思:给n个球,对应的质量为1~n,给m个约束关系:(a,b):编号为a的求比编号为b的球轻。
认真读题!!
输出编号1-n的球的重量;
题目要求输出字典序最小的,所以,编号大的球质量应该尽量大。所以逆序拓扑排序~
网上找的一个样例:
1
5 4
1 4
4 2
5 3
3 2
先得到编号的序列2 4 3 5 1,再与5 4 3 2 1一一对应,得到ans[2] = 5, ans[4] = 4, ans[3] = 3, ans[5] = 2, ans[1] = 1
从而找到输出答案1 5 3 4 2
附AC代码:
//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<vector>
#include<stack>
#include<cstdio>
using namespace std;
#define up(i,j,k) for(int i=j;i<k;i++)
#define uup(i,j,k) for(int i=j;i>=k;i--)
#define mem(i,j) memset(i,j,sizeof i)
#define sfi(i) scanf("%d",&i)
#define sfl(i) scanf("%lld",&i)
#define sfd(i) scanf("%lf",&i)
#define sfc(i) scanf("%c",&i)
#define sfs(i) scanf("%s",i)
#define sf() cout<<"This is a flag!"<<endl;
#define wt(i) cout<<"This is "<<i<<endl;
#define ll long long
#define mod(x) (x)%mod
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const int mod=10000;
const int MAX=5e2 +50;
struct node
{
int chudu;
int pre[MAX];
int t;
}p[MAX];
bool vis[MAX];
int num[MAX];
bool mapp[MAX][MAX];
int main()
{
//freopen("e:\\1.txt","r",stdin);
int T;
sfi(T);
while(T--)
{
int n,m;
sfi(n);
sfi(m);
mem(mapp,0);
mem(p,0);
int a,b;
int flag=0;
up(i,1,m+1)
{
sfi(a);
sfi(b);
if(!mapp[a][b])
mapp[a][b]=1;
else
continue;
if(a==b)
{
flag=1;
continue;
}
p[a].chudu++;
p[b].pre[p[b].t++]=a;
}
if(flag)
printf("-1\n");
else{
mem(vis,0);
uup(i,n,1)
{
int xx=-1;
uup(j,n,1)
{
if(!vis[j]&&p[j].chudu==0)
{
//wt(j);
xx=j;
break;
}
}
//sf();
if(xx==-1)
{
flag=1;
break;
}
vis[xx]=1;
num[xx]=i;
for(int j=0;j<p[xx].t;j++)
{
p[p[xx].pre[j]].chudu--;
//wt(p[p[xx].pre[j]].chudu);
}
}
if(flag)
{
printf("-1\n");
}
else{
up(i,1,n)
{
printf("%d ",num[i]);
}
printf("%d\n",num[n]);
}
}
}
return 0;
}