题目描述

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

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

代码其实没什么意思。

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如果没出现在描述的父子关系中呢?好坑……

 posted on 2015-05-05 21:21  xblade  阅读(110)  评论(0编辑  收藏  举报