hihoCoder 1041 国庆出游 最详细的解题报告

题目来源:国庆出游

解题思路(下面是大神的写的):

把题目中的序列称作S,树称作T。那么对于S中的任意节点x,x的子孙节点如果在S出现的话,那么这个子孙节点的位置是有一定要求的:x的所有子孙节点在S中的位置都恰好紧跟在x的后面,没有被其他节点隔开。 设x的子孙节点是abcd,那么--xabcd--, --xbcda-- 等等是合法的,--xab-cd--, --axbcd--, --x--abcd--, 都是不合法的('-'指其他节点)。对于S中每个节点都做如上判断,如果有不合法的就输出NO,如果都合法就输出YES。

感谢两位大神gtdzxaprilzc,解题思路是gtdzx大神提供的,代码参考aprilzc大神的

具体算法(java版,可以直接AC)

 import java.util.Scanner;

 public class Main {
//判断child是否为father的子孙节点
public static boolean isAncestor(int[] tree, int father, int child) {
while (tree[child] != child) {
child = tree[child];//将child的父节点赋值给child
if (father == child)
return true;
}
return false;
} public static boolean judge(int[] tree, int[] array, int start, int end) {
if (start >= end)//所有节点都检查完了
return true;
int k = start + 1;//当前节点的下一个节点
//依次计算当前节点start后面的节点是否为它的子孙节点(这些节点必须是连续的)
while (k <= end && isAncestor(tree, array[start], array[k])) {
k++;
}
//如果后面所有的节点均是start的子孙节点
//说明该节点的已经通过检查,然后判断下一个当前节点(start+1)
if (k >= end) {
return judge(tree, array, start + 1, end);
}
int v = k + 1;
//判断后面的节点(除连续子孙节点外,k是第一个非连续子孙节点)
//是否为start的子孙节点,如果是,说明存在一个非连续的子孙节点,
//直接return false
while (v <= end) {
if (!isAncestor(tree, array[start], array[v])) {
return false;
}
v++;
} //start已经检查完了,用来判断后面的节点(start+1)
return judge(tree, array, start+1,end); //大神的最后一句代码如下:
//return judge(tree, array, start, k - 1) && judge(tree, array, k, end);
//个人觉得效果是一样的
} public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int i = 0; i < T; i++) {
int n = scanner.nextInt();
int[] tree = new int[n + 1];
tree[1] = 1;
for (int j = 0; j < n - 1; j++) {
int father = scanner.nextInt();
int child = scanner.nextInt();
tree[child] = father;
}
int m = scanner.nextInt();
int[] array = new int[m];
for (int j = 0; j < m; j++) {
array[j] = scanner.nextInt();
}
if (judge(tree, array, 0, array.length - 1)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
scanner.close();
}
}
上一篇:hihoCoder 1041 国庆出游 (DFS)


下一篇:【面试题041】和为s的两个数字VS和为s的连续正数序列