【九度OJ】1035【Floyd算法】

抽象成图。

代码:

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");
		}
			
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值