C++数据结构关于树的问题

小明种了一棵果树,这棵树有 n 个节点,树根为 1 号节点,现在这颗果树上有 m 个节 点长出果实(根节点 1 有可能长出果实),小明要从节点 1 出发采集这些果实,从一个节点爬 到相邻的另一个节点所需要的时间为 1,采集果实不需要时间,问小明如果要采集这 m 个果 实,从节点 1 出发,并且最后需要回到节点 1,最少需要多少的时间。 (节点编号 1 到 n)
★数据输入
第 1 行输入两个数字 n 和 m
第 2 行到第 n 行每行输入两个数字 a 和 b 表示节点 a 和节点 b 之间有一条边
第 n+1 行输入 m 个数字,第 i 个数字 v[i]表示在 v[i]号节点上长有果实
n<=100000
0<m<=n
★数据输出
对于每个输入,输出一个数字,表示最少需要花费的时间。
输入示例
4 2
1 2
1 3
2 4
2 3
输出示例
4

#include<stdio.h>

#define MAX_NO 1000

typedef struct node{
int val; //access flag
unsigned ref; //parent reference
}*Node; //upside down tree node

struct node all[MAX_NO + 1];
unsigned input[MAX_NO + 1][2];
unsigned list[MAX_NO + 1];
int main()
{
int test, i;
scanf("%d", &test);
for(i = 1; i < test; i++)
scanf ("%d%d", input[i], input[i] + 1);
for(i = 1; i <= test; i++)
scanf("%d",list + i);
for(i = 1; i < test; i++)
all[input[i][0]].ref = input[i][1];
/* init */
all[list[1]].val = 1;
for(i = 2; i <= test; i++)
{
all[list[i]].val = 1; //set flag
if(all[all[list[i]].ref].val == 0)
{
printf("No");
return 0;
}
}
printf("Yes");
return 0;
}
温馨提示:答案为网友推荐,仅供参考