抽象成图。
代码:
package Test1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Test30_1035 {
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
// Floyd算法是一个经典的动态规划算法
while (true) {
st.nextToken();
int n = (int) st.nval;
st.nextToken();
int m = (int) st.nval;
if (n == 0 && m == 0)
break;
int dist[][] = new int[27][27]; // 1--->26
for (int i = 1; i <= 26; i++){
for (int j = 1; j <= 26; j++){
dist[i][j] = 1000000; //设为Integer.MAX_VALUE 相加时会溢出
}
dist[i][i]=0;
}
String str;
int child, parent1, parent2;
for (int i = 0; i < n; i++) {
st.nextToken();
str = st.sval;
child = str.charAt(0) - 64; // 从1开始
parent1 = str.charAt(1) - 64;
parent2 = str.charAt(2) - 64;
if(parent1<=26 && parent1>=1)
dist[parent1][child]=1; //有向图 父母指向孩子
if(parent2<=26 && parent2>=1)
dist[parent2][child]=1;
}
for(int k=1;k<=26;k++)
for(int i=1;i<=26;i++)
for(int j=1;j<=26;j++){
if(dist[i][k]+dist[k][j]<dist[i][j]){
dist[i][j]=dist[i][k]+dist[k][j];
}
}
int people1, people2;
for (int i = 0; i < m; i++) {
st.nextToken();
str = st.sval;
people1 = str.charAt(0) - 64;
people2 = str.charAt(1) - 64;
if(dist[people1][people2]!=1000000){
print(dist[people1][people2],1);
}else if(dist[people2][people1]!=1000000){
print(dist[people2][people1],0);
}else{
System.out.println("-");
}
}
}
}
private static void print(int i,int flag) {
if(i==1){
if(flag==1)
System.out.println("child");
else
System.out.println("parent");
}else if(i==2){
if(flag==1)
System.out.println("grandparent");
else
System.out.println("grandchild");
}else{
int n=i-2;
for(int j=0;j<n;j++)
System.out.print("great-");
if(flag==1)
System.out.println("grandparent");
else
System.out.println("grandchild");
}
}
}