This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<stdio.h>
#include<string.h>
#define N 200000
#define N_ (N+1)
int n, m, c[N_], head[N_], vv[N_<<1], nxt[N_<<1], i, u, v, far,dd[N_], rt, orz[N_], oo, hh[N_], longc[N_][2], fr[N_], dist, ans[N_];
void link(int u,int v)
{
static int i=1;
nxt[i]=head[u];
vv[i]=v;
head[u]=i++;
}
void dfs0(int u,int p)
{
dd[u]=dd[p]+1;
if(dd[u]>dd[far])far=u;
for(int j=head[u];j;j=nxt[j])if(vv[j]-p)dfs0(vv[j],u);
}
void dfs1(int u,int p)
{
dd[u]=dd[p]+1;
hh[u]=0;
for(int j=head[u];j;j=nxt[j])if(vv[j]-p)
{
dfs1(vv[j],u);
if(hh[vv[j]]>hh[longc[u][0]])
longc[u][1]=longc[u][0],longc[u][0]=vv[j];
else if(hh[vv[j]]>hh[longc[u][1]])
longc[u][1]=vv[j];
}
hh[u]=hh[longc[u][0]]+1;
}
void del(int x) { dist-=!--fr[x]; }
void ins(int x) { dist+=!fr[x]++; }
void dfs2(int u,int p)
{
if(p)ins(c[p]),orz[++oo]=p;
if(longc[u][0])
{
while(oo&&dd[u]-dd[orz[oo]]<=hh[longc[u][1]])
del(c[orz[oo--]]);
dfs2(longc[u][0],u);
}
while(oo&&dd[u]-dd[orz[oo]]<=hh[longc[u][0]])
del(c[orz[oo--]]);
for(int j=head[u];j;j=nxt[j])if(vv[j]-p&&vv[j]-longc[u][0])
dfs2(vv[j],u);
if(dist>ans[u])ans[u]=dist;
if(orz[oo]==p)del(c[orz[oo--]]);
}
void solve(int u)
{
dfs0(u,0);
rt=far;
dfs1(rt,0);
dfs2(rt,0);
oo=dist=0;
memset(longc,0,sizeof longc);
memset(fr,0,sizeof fr);
}
int main()
{
scanf("%d%d",&n,&m);
for(i=1;i<n;++i)scanf("%d%d",&u,&v),link(u,v),link(v,u);
for(i=1;i<=n;++i)scanf("%d",c+i);
solve(1);
solve(rt);
for(i=1;i<=n;++i)printf("%d\n",ans[i]);
}
Compilation message (stderr)
joi2019_ho_t5.c: In function 'main':
joi2019_ho_t5.c:74:5: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
74 | scanf("%d%d",&n,&m);
| ^~~~~~~~~~~~~~~~~~~
joi2019_ho_t5.c:75:21: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
75 | for(i=1;i<n;++i)scanf("%d%d",&u,&v),link(u,v),link(v,u);
| ^~~~~~~~~~~~~~~~~~~
joi2019_ho_t5.c:76:22: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
76 | for(i=1;i<=n;++i)scanf("%d",c+i);
| ^~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |