Description
Windy has Nballs of distinct weights from 1 unit to Nunits. Now he tries to label them with 1 to Nin such a way that:
-
No two balls sharethe same label.
-
The labelingsatisfies several constrains like "The ball labeled with ais lighter than the one labeled with b".
Can you help windy tofind a solution?
Input
The first line ofinput is the number of test case. The first line of each test casecontains two integers, N(1 ≤ N ≤ 200) andM (0 ≤ M≤ 40,000). The next Mline each contain two integers aand b indicating theball labeled with amust 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 caseoutput on a single line the balls' weights from label 1 to label N.If several solutions exist, you should output the one with thesmallest weight for label 1, then with the smallest weight for label2, then with the smallest weight for label 3 and so on... If nosolution exists, output -1 instead.
SampleInput
5
4 0
4 1
1 1
4 2
1 2
2 1
4 1
2 1
4 1
3 2
SampleOutput
1 2 3 4
-1
-1
2 1 3 4
1 3 2 4
算法思路:拓扑排序,先将图输入到矩阵中,对于每个点来说,每行的和表示出度,每列的和表示入度。ID从小到大进入队,依次检查每个顶点,如果入度为0,删除该点,并在下次计算入度时,不再加上该行的值。如果没有入度为0的点,程序就结束。
package OJ;
import java.util.*;
public class P14_temp {
public static void main(String[] args) {
class Vertex {
int export;
int num;
public Vertex(int num){
export = 0;
this.num = num;
}
public Vertex(int num, int export){
this.export = export;
this.num = num;
}
public void addEx(){
export++;
}
public void removeEx(int ex){
export = export -ex;
}
public int getNum(){
return num;
}
public int getEx(){
return export;
}
}
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
while(cases > 0){
int arraysize = in.nextInt(); //二维数组的宽度
int[][] graph = new int[arraysize][arraysize];
ArrayList<Vertex> vertexs = new ArrayList<Vertex>();//顶点集合
for(int k=0; k<arraysize; k++)
vertexs.add(new Vertex(k+1));
int inputrows = in.nextInt();
while(inputrows > 0){
int i = in.nextInt()-1;
int j = in.nextInt()-1;
graph[i][j] = 1;
vertexs.get(i).addEx();
inputrows--;
}
ArrayList<Integer> result = new ArrayList<Integer>();
for(int t=vertexs.size()-1; t>-1;){
if(vertexs.get(t).getEx() == 0){
result.add(vertexs.get(t).getNum());
for(int m=0; m<arraysize; m++){
if(graph[m][t] == 1){
graph[m][t] = 0;
vertexs.get(m).removeEx(1);
}
}
vertexs.remove(t);
t = vertexs.size()-1;
continue;
}
t--;
}
if(vertexs.size() != 0){
result.clear();
result.add(-1);
results.add(result);
}
else
results.add(result);
cases--;
}
for(int n=0; n<results.size(); n++){
for(int r=results.get(n).size()-1; r >-1; r--){
if(r == 0){
System.out.println(results.get(n).get(r));
}
else
System.out.print(results.get(n).get(r) + " ");
}
}
}
}