程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> POJ 3687

POJ 3687

編輯:關於C++

Labeling Balls Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11256 Accepted: 3230

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, 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 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

題意:有T組測試數據,每組測試數據第一行有兩個數n,m。代表有n個球,接下來m行,每行有兩個數a,b,代表a球比b球輕,讓你從小到大輸出球的重量,若是相同重量,按照字典序輸出。

思路:這個和以前的拓撲排序略微不同,不是考慮入度為0的情況。因為假設n為4,4<1.則輸出的列是2,3,4,1,而不是按照以前所說的 4,1,2,3.所以要考慮的是先把最重的放在後面,輕的在前面按照字典序輸出就可以了。


#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int map[210][210];
int out[210];
void topo(int n)
{
    int i;
    int cnt=n;
    int weight[210];
    priority_queueq;//優先隊列,按照從大到小排序。
    for(i=1;i<=n;i++){
        if(out[i]==0)
            q.push(i);
    }
    while(!q.empty()){
        int k=q.top();
        q.pop();
        weight[k]=cnt--;
        for(i=1;i<=n;i++){
            if(map[i][k]){
                out[i]--;
                if(out[i]==0)
                    q.push(i);
            }
        }
    }
    if(cnt>0)
        printf("-1\n");
    else{
        for(i=1;i

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved