poj3687
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9028 | Accepted: 2444 |
Description
Windy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 toN 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 withb".
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 nextM line each contain two integersa and b indicating the ball labeled witha must be lighter than the one labeled withb. (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 labelN. 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
#include<iostream> #include<stdio.h> #include<queue> using namespace std; typedef struct v{ int vex; v *next; }V; V*p; typedef struct h{ int indegree; v *next ; }H; int n,result[300],tot,ans[300]; priority_queue<int ,vector<int>,less<int> > q; H team[50000]; bool visit[305][305]; void topsort() { int i,ci,sum,a,b; ci=1; for(i=1;i<=n;i++) { if(team[i].indegree==0) q.push(i); } sum=n; while(!q.empty()) { sum--; a=q.top(); q.pop(); result[ci++]=a; for(p=team[a].next;p!=0;p=p->next) { b=p->vex; if(--team[b].indegree==0) q.push(b); } } // printf("%d\n",sum); if(sum>0) { printf("-1\n"); } else { int nn=n; for(i=1;i<=n;i++) { ans[result[i]]=nn--;//这是排序 } for(i=1;i<n;i++) printf("%d ",ans[i]);//这是重量 printf("%d\n",ans[i]); } } int main() { int i,m,a,b,T,j; scanf("%d",&T); while(T--) { while(!q.empty()) { q.pop(); } scanf("%d%d",&n,&m); for(i=0;i<=n;i++) for(j=0;j<=n;j++) { visit[i][j]=false; } for(i=0;i<=n;i++) { team[i].indegree=0; team[i].next=NULL; result[i]=0; } while(m--) { scanf("%d%d",&b,&a);//反向建表 if(visit[a][b]) continue; visit[a][b]=true; team[b].indegree++; p=new V; p->vex=b; p->next=team[a].next; team[a].next=p; } topsort(); } return 0; }