PAT(甲级)2021年冬季考试 7-3 Size of Military Unit

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<stdio.h>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 100010;
int ans[maxn];
struct Node{
    vector<int> child;
}node[maxn];
int dfs(int root){
    if(node[root].child.size() == 0) {
        ans[root] = 0;    
        return 0;
    }
    int x = 0;
    for(int i = 0; i < node[root].child.size(); i++){
        x += dfs(node[root].child[i]) + 1;
    }
   ans[root] = x;
   return ans[root];
}
int main(){
    int N;
    scanf("%d", &N);
    for(int i = 0; i < N-1; i++){
        int senior;
        scanf("%d", &senior);
        node[senior].child.push_back(i+2);
    }
    int M;
    scanf("%d", &M);
    dfs(1);
    for(int i = 0; i < M; i++){
        int query, count = 0;
        scanf("%d", &query);
        
        printf("%d\n", ans[query] + 1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值