7-3 Size of Military Unit (25 分)

本文介绍了一个基于记忆化搜索算法来解决军队单位规模计算的问题。给定士兵及其上级军官的列表,通过递归算法计算出每个特定单位的具体人数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

7-3 Size of Military Unit (25 分)

The Army is a large organization, made up of many different branches and groups. Each group is called a “unit”. The Army has a hierarchical structure (等级结构) – that is, each senior officer gives commands to many units, and the commander of a unit reports to the only senior officer who gives commands directly to him/her. There is a unique General of the Armies who holds the highest rank.

Now given the list of soldiers and their senior officers, your job is to tell the size (number of soldiers) of any specific unit.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (2≤N≤105), which is the total number of soldiers in the army. Assume all the soldiers are numbered from 1 to N, and General of the Armies is always the number 1. Then the next line gives N−1 numbers, each corresponds to an officer or a soldier numbered from 2 to N. The ith number corresponds the only senior officer who gives commands directly to the ith soldier. Notice that since General of the Armies holds the highest rank and is the number 1, the above list starts from the 2nd officer/soldier.

Then a positive integer M (≤N), the number of queries, is given in a line. Followed in the next line are M numbers, each represents a soldier.

Output Specification:
For each soldier in a query, output in a line the size of his/her unit.

Sample Input (the structure is shown by the figure below):

10
4 6 6 8 1 8 1 8 8
4
8 6 4 9

Sample Output:

5
4
2
1

记忆化搜索,每次搜存每个点

#include <iostream> 
#include <vector>
using namespace std;
vector<int> v[100100];
int ans[100100];
int dfs(int x) {
	for(int i = 0; i < v[x].size(); ++i)
		ans[x] += dfs(v[x][i]);
	return ans[x] = ans[x] + 1;
}
int main() {
	int n, m, x;
	scanf("%d", &n);
	for(int i = 2; i <= n; ++i) {
		scanf("%d", &x);
		v[x].push_back(i);
	}
	dfs(1);
	scanf("%d", &m);
	while(m--) {
		scanf("%d", &x);
		printf("%d\n", ans[x]);
	}
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值