import java.util.Scanner; /** * 1330 Nearest Common Ancestors * Time Limit: 1000MS Memory Limit: 10000K * Total Submissions: 4632 Accepted: 2438 * @author zhtsuc * */ public class NearestCommonAnestor { private int[] arr; public void solve(){ Scanner in = new Scanner(System.in); int caseNum = in.nextInt(); while(caseNum != 0){ int nodeNum = in.nextInt(); arr = new int[nodeNum + 1]; for(int i = 1; i <= nodeNum - 1; i++){ int parentNode = in.nextInt(); int childNode = in.nextInt(); arr[childNode] = parentNode; } int firstNode = in.nextInt(); int secondNode = in.nextInt(); int nearestCommonAnestor = getNearestCommonAnestor(firstNode, secondNode); System.out.println(nearestCommonAnestor); caseNum--; } } private int getNearestCommonAnestor(int firstNode, int secondNode){ while(firstNode != 0){ if (isParent(secondNode, firstNode)){ return firstNode; } firstNode = arr[firstNode]; } return -1; } private boolean isParent(int srcNode, int parentNode){ int node = srcNode; while(node != 0){ if (node == parentNode){ return true; } node = arr[node]; } return false; } public static void main(String[] args) { NearestCommonAnestor tree = new NearestCommonAnestor(); tree.solve(); } }
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
QQ咨询|关于我们|Archiver|手机版|小黑屋|( 辽ICP备15012455号-4 ) Powered by 期权论坛 X3.2 © 2001-2016 期权工具网&期权论坛 Inc.
下载期权论坛手机APP