[hiho 13]最近公共祖先 一

题目描述

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

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

代码其实没什么意思。

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

转载于:https://www.cnblogs.com/xblade/p/4480332.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值