Labeling Balls
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 13109
Accepted: 3782
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:
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
思路:拓扑排序,优先队列。
开始时我是正向建边,然后拓扑排序,贪心去当前度为0的最小的点WA
后来想想,因为要保证1,2,。。。要最优,也就是要先找到1,那么在1前面度为0的点肯定在1之前。那么用上面这种贪心,我们会先选1,然后
4然后5,然后才是3,由于我们要先贪心找到2,所以这种策略就不对了,那么我们还是从正向模拟一下,1,5,3,4,2,这时正向走就是按每次最小所以我们的先找到2然后这时
这时2前面的数已经取出,但我们不知道在2出来前咋对前面的数进行选取。我们思考这么一种策略,我们建反向边,我们可以知道如果这时有入度为0的点,那么我们选取最大的
入度为0的点,这时这个点肯定是最后一个,那些在它下一层的那些点肯定排在它的前面,同时比它小和他同一层的点也要排在它的前面,所以每次都这样,选最大的可以保证最优。
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 using namespace std;
8 typedef struct pp {
9 int x;
10 bool operator<(const pp &n)const {
11 return n.x>x;
12 }
13 } ss;
14 vector
15 priority_queue
16 int ans[300];
17 int bb[300];
18 int aa[300];
19 int ma[300][300];
20 int main(void) {
21 int i,j,k;
22 int p,q;
23 scanf("%d",&k);
24 while(k--) {
25 for(i=0; i<300; i++) {
26 vec[i].clear();
27 }
28 while(!que.empty())que.pop();
29 memset(ma,0,sizeof(ma));
30 memset(ans,0,sizeof(ans));
31 scanf("%d %d",&p,&q);
32 int ff=0;
33 while(q--) {
34 int x,y;
35 scanf("%d %d",&x,&y);
36 if(x==y)ff=1;
37 {
38 vec[y].push_back(x);
39 ans[x]++;
40 ma[y][x]=1;
41 }
42 }
43 if(ff)printf("-1\n");
44 else {
45 int flag=0;
46 for(i=1; i<=p; i++) {
47 if(ans[i]==0) {
48 ss g;
49 g.x=i;
50 que.push(g);
51 }
52 }
53 while(!que.empty()) {
54 ss fg=que.top();
55 int c=fg.x;
56 bb[flag++]=c;
57 que.pop();
58 for(i=0; i<vec[c].size(); i++) {
59 int uu=vec[c][i];
60 ans[uu]--;
61 fg.x=uu;
62 if(ans[uu]==0) {
63 que.push(fg);
64 }
65 }
66 }
67 if(flag==p) {
68 for(i=0; i<p; i++) {
69 aa[bb[i]]=p-i;
70 }
71 printf("%d",aa[1]);
72 for(i=2; i<=p; i++) {
73 printf(" %d",aa[i]);
74 }
75 printf("\n");
76 } else printf("-1\n");
77 }
78 }
79 return 0;
80 }
手机扫一扫
移动阅读更方便
你可能感兴趣的文章