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<bits/stdc++.h>
#pragma GCC optimize("unroll-loops,no-stack-protector")
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
const ll MOD=1e9+7;
const ll MOD2=998244353;
const ll N=4e5+5;
const ll K=350;
const ld pi=acos(-1);
const ll INF=(1LL<<60);
#define SQ(i) ((i)*(i))
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define setp setprecision
#define lwb lower_bound
#define SZ(_a) (ll)_a.size()
ll n,m,x,y,cnt[N],stk[N],res,ans[N],ed,h[N],d[N],son[N][2],rt,col[N];
vector<ll> v[N];
void add(ll k){
if(cnt[k]==0)++res;
++cnt[k];
}
void del(ll k){
if(cnt[k]==1)--res;
--cnt[k];
}
void DFS1(ll nd,ll pa){
d[nd]=d[pa]+1;
if(d[nd]>d[rt])rt=nd;
for(auto i:v[nd]){
if(i==pa)continue;
DFS1(i,nd);
}
}
void DFS2(ll nd,ll pa){
d[nd]=d[pa]+1;
son[nd][0]=son[nd][1]=0;
for(auto i:v[nd]){
if(i==pa)continue;
DFS2(i,nd);
for(ll j=0,tmp=i;j<2;j++){
if(h[tmp]>=h[son[nd][j]])swap(tmp,son[nd][j]);
}
}
h[nd]=h[son[nd][0]]+1;
}
void DFS3(ll nd,ll pa){
if(pa){add(col[pa]);stk[++ed]=pa;}
if(son[nd][0]){
while(~ed&&d[stk[ed]]>=d[nd]-h[son[nd][1]])del(col[stk[ed]]),--ed;
DFS3(son[nd][0],nd);
}
while (~ed&& d[stk[ed]] >= d[nd] - h[son[nd][0]])del(col[stk[ed]]),--ed;
for(auto i:v[nd]){
if(i==pa||i==son[nd][0])continue;
DFS3(i,nd);
}
ans[nd]=max(ans[nd],res);
if(stk[ed]==pa)del(col[stk[ed]]),--ed;
}
void work(ll nd){
rt=nd;
DFS1(nd,0);
DFS2(rt,0);
REP1(i,m)cnt[i]=0;
res=0;
ed=-1;
DFS3(rt,0);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n>>m;
REP(i,n-1){
cin>>x>>y;
v[x].pb(y);v[y].pb(x);
}
REP1(i,n)cin>>col[i];
//d[0]=-1;
work(1);
work(rt);
REP1(i,n)cout<<ans[i]<<"\n";
return 0;
}
# | 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... |