Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11229 | Accepted: 3223 |
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.
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
题意:N个标签分别是1,2,3......N。N个小球,质量分别是1,2,3.....N。现在给球贴标签,有M个限制条件。其中每个限制条件为贴标签a的球要比贴标签b的球轻。依次输出标签1的球的质量,标签2的球的质量.........且字典序最小。
题解:如果没有字典序最小的限制条件,那么标签a比标签b轻,则建一条边从a到b。如果图存在环在,则无解。如果图没环,直接进行拓扑排序,将每次选出的点贴给当前最小的质量的球,即可求得一组解。
要让字典序最小,建上一个图的反向图,进行拓扑排序,拓扑排序的过程中每次选当前度为0的点中标号最大的,将该标签贴给当前最大质量的球即可。(证明还没搞清楚。。。)
代码如下:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<queue>
#include<vector>
#define nn 210
#define inff 0x3fffffff
using namespace std;
int n,m;
struct node
{
int en,next;
}E[nn*nn];
int p[nn],num;
void init()
{
memset(p,-1,sizeof(p));
num=0;
}
void add(int st,int en)
{
E[num].en=en;
E[num].next=p[st];
p[st]=num++;
}
int rd[nn];
priority_queue<int>que;
int ans[nn];
int dp[nn];
bool use[nn];
int main()
{
int t,i,u,v,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
init();
memset(rd,0,sizeof(rd));
for(i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(v,u);
rd[u]++;
}
for(i=1;i<=n;i++)
{
if(rd[i]==0)
{
que.push(i);
}
}
int ix;
int id=n,w;
while(que.size())
{
ix=que.top();
que.pop();
ans[ix]=id--;
for(i=p[ix];i+1;i=E[i].next)
{
w=E[i].en;
rd[w]--;
if(rd[w]==0)
que.push(w);
}
}
if(id>0)
{
puts("-1");
}
else
{
for(i=1;i<=n;i++)
{
printf("%d%c",ans[i],i==n?'\n':' ');
}
}
}
return 0;
}