题解 | #小红的树#

小红的树

https://www.nowcoder.com/practice/66ab364d3fba487eb39bd3460fd484c0

遍历每个颜色red[i]:
如果red[i]=1 (R):将自身以及它的父节点,以及父节点的父节点... 让他们的cnt[父->父]++

每次询问直接输出cnt[q]即可

#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5+10;
int par[N];
int red[N];
int cnt[N];
int n;
int main() {
    cin >> n;
    int p;
    memset(par, -1, sizeof(par));
    for(int i = 2; i <= n; i++){
        cin >> p;
        par[i] = p;
    }
    string c;
    cin >> c;
    for(int i = 0; i < n; i++){
        if(c[i]=='R'){
            red[i+1]=1;
        }
    }
    for(int i = 1; i <= n; i++){
        if(red[i]==1){
            cnt[i]++;
            int tmp = par[i];
            while(tmp!=-1){
                cnt[tmp]++;
                tmp = par[tmp];
            }
        }
    }
    int q,t;
    cin >> q;
    while(q--){
        cin >> t;
        cout << cnt[t] << endl;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务