1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include<bits/stdc++.h> using namespace std;
void read(int &x) { x=0;int f=1;char ch=getchar(); for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-f; for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';x*=f; }
void print(int x) { if(x<0) putchar('-'),x=-x; if(!x) return ;print(x/10),putchar(x%10+48); } void write(int x) {if(!x) putchar('0');else print(x);putchar('\n');}
#define lf double #define ll long long
#define pii pair<int,int > #define vec vector<int >
#define pb push_back #define mp make_pair #define fr first #define sc second
#define FOR(i,l,r) for(int i=l,i##_r=r;i<=i##_r;i++)
const int maxn = 1e6+10; const int inf = 1e9; const lf eps = 1e-8; const int mod = 1e9+7;
int n,m,head[maxn],tot,a[maxn],cnt,dep[maxn],d[maxn],s[maxn],ans[maxn],sta[maxn],top,r[maxn]; struct edge{int to,nxt;}e[maxn<<1];
void ins(int u,int v) {e[++tot]=(edge){v,head[u]},head[u]=tot;}
void get(int x,int fa) { d[x]=d[fa]+1;s[x]=0; for(int i=head[x];i;i=e[i].nxt) if(e[i].to!=fa) { get(e[i].to,x); if(dep[e[i].to]>dep[s[x]]) s[x]=e[i].to; } dep[x]=dep[s[x]]+1; }
void push(int x) { if(!r[a[x]]) cnt++; r[a[x]]++;sta[++top]=x; }
void pop(int x=sta[top]) { if(r[a[x]]==1) cnt--;r[a[x]]--;top--; }
void solve(int x,int fa) { int mx=0; for(int i=head[x];i;i=e[i].nxt) if(e[i].to!=fa&&e[i].to!=s[x]) mx=max(mx,dep[e[i].to]); while(top&&d[x]-d[sta[top]]<=mx) pop(); push(x);if(s[x]) solve(s[x],x); for(int i=head[x];i;i=e[i].nxt) if(e[i].to!=fa&&e[i].to!=s[x]) { while(top&&d[x]-d[sta[top]]<=dep[s[x]]) pop();push(x); solve(e[i].to,x); } while(top&&d[x]-d[sta[top]]<=dep[s[x]]) pop(); ans[x]=max(ans[x],cnt); }
int main() { read(n),read(m); for(int i=1,x,y;i<n;i++) read(x),read(y),ins(x,y),ins(y,x); for(int i=1;i<=n;i++) read(a[i]); get(1,0);int x=0; for(int i=1;i<=n;i++) if(d[i]>d[x]) x=i; get(x,0);solve(x,0); for(int i=1;i<=n;i++) if(d[i]>d[x]) x=i; get(x,0),solve(x,0); for(int i=1;i<=n;i++) write(ans[i]); return 0; }
|