码迷,mamicode.com
首页 > 其他好文 > 详细

[hiho 13]最近公共祖先 一

时间:2015-05-05 23:32:07      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

由于这个跟后几周是一个系列,这周的做法比较简单。

把第一个人的所有祖先做标记,第二个人向上查找祖先直到找到一个标记过的节点或无法继续为止。

代码其实没什么意思。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
	
public class Main {
	private static class Person {
		String name;
		String father;
		boolean tag = false;
		protected Person(String name, String father) {
			this.name = name;
			this.father = father;
		}
	}
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();in.nextLine();
        Map<String, Person> heritage = new HashMap<String, Person>();
        for (int i = 0; i < n; i++) {
        	String line = in.nextLine();
        	String[] people = line.split(" ");
        	String father = people[0];
        	String son = people[1];
        	Person newPerson = new Person(son, father);
        	heritage.remove(son);
        	heritage.put(son, newPerson);
        	if (heritage.get(father) == null) {
        		Person newFather = new Person(father, null);
        		heritage.put(father, newFather);
        	}
        }
        int m = in.nextInt();in.nextLine();
        for (int i = 0; i < m; i++) {
        	String line = in.nextLine();
        	String[] people = line.split(" ");
        	if (people[0].equals(people[1])) {
        		System.out.println(people[0]);
        		continue;
        	}
        	Person p1 = heritage.get(people[0]);
        	Person p2 = heritage.get(people[1]);
        	Person pt = p1;
        	while (p1 != null) {
        		pt.tag = true;
        		if (pt.father == null) {
        			break;
        		} else {
        			pt = heritage.get(pt.father);
        		}
        	}
        	pt = p2;
        	while (pt != null && pt.tag == false) {
        		if (pt.father == null) {
        			break;
        		} else {
        			pt = heritage.get(pt.father);
        		}
        	}
        	if (pt == null || pt.tag == false) {
        		System.out.println(-1);
        	} else {
        		System.out.println(pt.name);
        	}
        	pt = p1;
        	while (p1 != null) {
        		pt.tag = false;
        		if (pt.father == null) {
        			break;
        		} else {
        			pt = heritage.get(pt.father);
        		}
        	}
        }
        heritage.clear();
        in.close();
    }
}

吐槽:A和A的公共祖先是谁?A如果没出现在描述的父子关系中呢?好坑……

[hiho 13]最近公共祖先 一

标签:

原文地址:http://www.cnblogs.com/xblade/p/4480332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!