poj-3687 Labeling Balls

来源:互联网 发布:stm32jlink 烧录软件 编辑:程序博客网 时间:2024/06/05 19:46

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:

  1. No two balls share the same label.
  2. 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 integers a and b indicating the ball labeled witha must be lighter than the one labeled with b. (1 ≤ a, bN) 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

54 04 11 14 21 22 14 12 14 13 2

Sample Output

1 2 3 4-1-12 1 3 41 3 2 4

    题意是输入的球的关系为前一个比后一个轻,而题目要求把重的球放到后面,轻的球在前面且序号小的在前面,所以需要反向的拓扑排序。最后输出每个球所在的位置。

#include <iostream>#include <stdio.h>#include <string.h>#include <stdlib.h>#define INF 0x3f3f3f3fusing namespace std;int du[255];int map[255][255];int vis[255];int ans[255];int main(){    int n,m,x,y;    int t,i,j,k;    scanf("%d",&t);    while (t--)    {        memset(map,0,sizeof(map));        memset(du,0,sizeof(du));        scanf("%d%d",&n,&m);        for (i=0; i<m; i++)        {            scanf("%d%d",&x,&y);            if(!map[y][x])            {                map[y][x]=1;                du[x]++;            }        }        int flag;        for (i=n; i>=1; i--)        {            flag=1;            for (j=n; j>=1; j--)            {                if(du[j]==0)                {                    flag=0;                    ans[j]=i;                    du[j]=-1;                    for (k=1; k<=n; k++)                    {                        if(map[j][k])                            du[k]--;                    }                    break;                }            }            if (flag) break;        }        if(flag)        {            printf("-1\n");        }        else        {            for (i=1; i<=n; i++)            {                printf("%d%c",ans[i],i==n?'\n':' ');            }        }    }    return 0;}


0 0
原创粉丝点击