poj 1094 Sorting It All Out(java + 拓扑排序)

完全没看懂是怎么回事,还是看的别人的代码调试出来的
特殊测试数据
2 2

A
B
要输出

Sorted sequence determined after 1 relations: AB.
 
   

package 拓扑排序;

import java.util.Scanner;

/**问题请参考
* @author rayli

* @date:2014-7-30 上午9:51:58
* @version :
*
*/
public class SortingAllout
{
static int n;
static int m;
static int map[][];
static int re[];

int d[] = new int[n];
int topo(String s, int n)
{
char tmp[] = s.toCharArray();

int du[] = new int[n];

int one = tmp[0] - 'A';
int two = tmp[2] - 'A';

if(map[one][two] == 0)
{
map[one][two] = 1;
d[two]++;
}

for(int i=0; i du[i] = d[i];

int w = 0;
int cnt;
int repos = 0;
boolean flag = true;

for(int i=0; i {
cnt = 0;

for(int j=0; j {
if(du[j] == 0)
{
w = j;
cnt ++;
}
}

if(cnt == 0)
return -1;
else if(cnt > 1)
flag = false;//之前写成true

du[w]--;
re[repos++] = w;

for(int j =0; j {
if(map[w][j] == 1)
{
du[j]--;
}
}
}

if(flag)
return 1;
else
return 0;

}

public static void main(String args[])
{
Scanner cin = new Scanner(System.in);

n = cin.nextInt();
m = cin.nextInt();

while(n!=0 && m!=0)
{
map = new int[n][n];
re = new int[n];

if(n -1 > m)
{
for(int i=0; i {
cin.next();
}

System.out.println("Sorted sequence cannot be determined.");
}
else
{
SortingAllout sa = new SortingAllout();
// sa.ans(n, m);


String s;
boolean flag = true;

for(int i=0; i {
s = cin.next();

if(flag)
{
int t = sa.topo(s, n);

if(t == 1)
{
System.out.print("Sorted sequence determined after " + (i+1) + " relations: ");

for(int j=0; j {
System.out.print((char)(re[j] + 'A'));
}
System.out.println(".");

flag = false;
}
else if(t == -1)
{
System.out.println("Inconsistency found after " + (i+1) + " relations.");
flag = false;
}
}
}

if(flag)
System.out.println("Sorted sequence cannot be determined.");

}

n = cin.nextInt();
m = cin.nextInt();
}
cin.close();
}
}

你可能感兴趣的:(ACM)