685B - Kay and Snowflake - CodeForces Solution


data structures dfs and similar dp trees *1900

Please click on ads to support us..

C++ Code:

// Hydro submission #[email protected]
// 2022.07.26

#include<bits/stdc++.h>
using namespace std;

int n,q,f[300001];

struct Edge{
    int to,nxt;
}edge[600001];
int cntEdge,head[300001];
inline void addEdge(int u,int v){
    edge[++cntEdge]={v,head[u]},head[u]=cntEdge;
}

int siz[300001],g[300001];
void dp(int id){
    siz[id]=1;
    for(int i=head[id];i;i=edge[i].nxt)
        if(edge[i].to!=f[id]){
            dp(edge[i].to);
            siz[id]+=siz[edge[i].to];
        }
    int maxn=0;
    for(int i=head[id];i;i=edge[i].nxt)
        if(edge[i].to!=f[id]){
            int v=edge[i].to;
            if((siz[v]<<1)>=siz[id]&&siz[v]>maxn){
                maxn=siz[v];
                g[id]=g[v];
                while(g[id]!=id){
                    if((siz[g[id]]<<1)>=siz[id])break;
                    g[id]=f[g[id]];
                }
            }
        }
    if(!maxn)g[id]=id;
}

int main(){
    scanf("%d%d",&n,&q);
    for(int i=2;i<=n;i++){
        scanf("%d",f+i);
        addEdge(i,f[i]);
        addEdge(f[i],i);
    }
    dp(1);
    while(q--){
        int u; scanf("%d",&u);
        printf("%d\n",g[u]);
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1091A - New Year and the Christmas Ornament
1352B - Same Parity Summands
1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves
1670B - Dorms War
1716B - Permutation Chain
987A - Infinity Gauntlet
1676G - White-Black Balanced Subtrees
1716D - Chip Move
1352F - Binary String Reconstruction
1487B - Cat Cycle
1679C - Rooks Defenders
56A - Bar
1694B - Paranoid String
35A - Shell Game
1684A - Digit Minimization
43B - Letter
1017A - The Rank
1698B - Rising Sand
235A - LCM Challenge
1075B - Taxi drivers and Lyft