Labeling Balls
Time Limit: 1000MS |
| Memory Limit: 65536K |
Total Submissions: 7703 |
| Accepted: 2068 |
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
Source
小的头部不一定排在前面,但是大的尾部一定排在后面
开始一直中枪,题解中说的两种情况都中
最后终于发现是算法错了
唉,坑爹啊,这题目错误的算法样例都过
很丑的代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <algorithm>
#include <iomanip>
using namespace std;
#define maxn 210
#define pp printf("here\n")
bool mp[maxn][maxn],vis[maxn];
int indre[maxn];
bool q[maxn];
int head,tail,n,m;
struct point
{
int x,id;
} ans[maxn];
int num,num1,sec,se;
void add(int x,int id)
{
se++;
ans[se].x=x;
ans[se].id=id;
}
int cmp(point t1,point t2)
{
return t1.x<t2.x;
}
void topsort()
{
int i,j,tmp;
bool flag;
num=0;
num1=0;
sec=n;
se=0;
memset(q,0,sizeof(q));
memset(vis,0,sizeof(vis));
for(i=1; i<=n; i++)
{
if (indre[i]==0)
{
vis[i]=1;
q[i]=1;
num++;
num1++;
}
}
// printf("%d\n",num1);
while(num1)
{
num1--;
tmp=n+1;
while(--tmp)
{
if(q[tmp]==1) break;
}
q[tmp]=0;
add(tmp,sec);
sec--;
for(j=1; j<=n; j++)
if(mp[tmp][j]==1&&vis[j]==0)
{
indre[j]--;
}
for(j=1; j<=n; j++)
if(vis[j]==0&&indre[j]==0)
{
vis[j]=1;
q[j]=1;
num++;//pp;
num1++;
}
}
// printf("%d\n",num);
if(num!=n) printf("-1\n");
else
{
sort(ans+1,ans+n+1,cmp);
for(i=1; i<n; i++)
printf("%d ",ans[i].id);
printf("%d\n",ans[n].id);
}
}
int main()
{
int x,y,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(mp,0,sizeof(mp));
memset(indre,0,sizeof(indre));
for(int i=1; i<=m; i++)
{
scanf("%d%d",&x,&y);
if(!mp[y][x])
{
mp[y][x]=1;
indre[x]++;
}
}
topsort();
}
return 0;
}