Cod sursa(job #3361849)

Utilizator RaduBalasRadu Andrei Balas RaduBalas Data 28 iulie 2026 20:51:30
Problema Cerere Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.37 kb
#include <stdio.h>
#define maxn 100005
#define maxe 200005
int k[maxn],p[maxn],h[maxn],to[maxe],nx[maxe],ans[maxn],anc[maxn],stn[maxn],ste[maxn];
int main(){
    int n,i,x,y,m,r,s,top,idx,v,e,ei,u,d,td,tgt;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        scanf("%d",&k[i]);
    for(i=1;i<=n;i++)
        p[i]=h[i]=0;
    m=0;
    for(i=0; i<n-1; i++){
        scanf("%d%d",&x,&y);
        p[y]=x;
        m++;
        to[m]=y;
        nx[m]=h[x];
        h[x]=m;
    }
    r=1;
    for(i=1; i<=n; i++)
        if(p[i]==0){
            r=i;
            break;
        }
    for(i=1; i<=n; i++)
    ans[i]=0;
    s=top=0;
    stn[top]=r;
    ste[top]=-1;
    top++;
    while(top>0){
        idx=top-1;
        v=stn[idx];
        e=ste[idx];
        if(e==-1){
            anc[s]=v;
            s++;
            if(k[v]==0)
                ans[v]=0;
            else{
                d=s-1;
                td=d-k[v];
                tgt=anc[td];
                ans[v]=ans[tgt]+1;
            }
            ste[idx]=h[v];
        }
        else if(e!=0){
            ei=e;
            u=to[ei];
            ste[idx]=nx[ei];
            stn[top]=u;
            ste[top]=-1;
            top++;
        }
        else{
            s--;
            top--;
        }
    }
    for(i=1; i<=n; i++)
        printf("%d ",ans[i]);
    return 0;
}