魔法王国一共有n个城市,编号为0~n-1号,n个城市之间的道路连接起来恰好构成一棵树。
小易现在在0号城市,每次行动小易会从当前所在的城市走到与其相邻的一个城市,小易最多能行动L次。
如果小易到达过某个城市就视为小易游历过这个城市了,小易现在要制定好的旅游计划使他能游历最多的城市,请你帮他计算一下他最多能游历过多少个城市(注意0号城市已经游历了,游历过的城市不重复计算)。
输入包括两行,第一行包括两个正整数n(2 ≤ n ≤ 50)和L(1 ≤ L ≤ 100),表示城市个数和小易能行动的次数。 第二行包括n-1个整数parent[i](0 ≤ parent[i] ≤ i), 对于每个合法的i(0 ≤ i ≤ n - 2),在(i+1)号城市和parent[i]间有一条道路连接。
输出一个整数,表示小易最多能游历的城市数量。
5 2 0 1 2 3
3
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<iostream> using namespace std; typedef long long LL; int parent[60]; int dp[200]; int main() { int n, L; scanf_s("%d%d", &n, &L); for (int i = 0; i<n - 1; i++) { scanf_s("%d", &parent[i]); } int mx = 0; for (int i = 0; i<n - 1; i++) { for (int j = 0; j <= i; j++) { dp[j + 1] = max(dp[j + 1], dp[parent[j]] + 1); } mx = max(mx, dp[i + 1]); } int d = min(L, mx); printf("%d\n", min(n, 1 + d + (L - d) / 2)); return 0; }
有大佬看下这个为什么一直通过不了吗?看了半天了都没发现问题 def isSubStructure(self, pRoot1, pRoot2): """ :type A: TreeNode :type B: TreeNode :rtype: bool """ if not pRoot1 or not pRoot2: return False def is_sub_tree(tree1, tree2): #子结构已经循环完毕,代表全部匹配 if not tree2: return True # 大树已经循环完毕,并未成功匹配 if not tree1: return False if tree1.val == tree2.val: return is_sub_tree(tree1.left, tree2.left) and is_sub_tree(tree1.right, tree2.right) return False return is_sub_tree(pRoot1, pRoot2) or is_sub_tree(pRoot1.left, pRoot2) or is_sub_tree(pRoot1.right, pRoot2)
//https://blog.csdn.net/RPG_Zero/article/details/99562230 #include<iostream> #include<algorithm> using namespace std; int parent[52]; int dp[52]; int main() { int n, l; while (cin >> n >> l) { for (int i = 1; i <= n - 1; i++) { cin >> parent[i]; } dp[0] = 0; int hight = 0; for (int i = 1; i <= n - 1; i++) { dp[i] = dp[parent[i]] + 1; hight = max(hight, dp[i]);//求出树的深度 } if (l <= hight) { cout << l + 1 << endl; } else cout << min(n, hight + 1 + (l - hight) / 2);//注意最多也就是把所有的城市都游历完 } }