XXX on tree

%了发树上莫队

nlognsqrt(n)

// luogu-judger-enable-o2
#include<bits/stdc++.h> 
using namespace std; 
inline int read() { 
    int x = 0,f = 1; 
    char c = getchar(); 
    while(c < '0' || c > '9')c = getchar(); 
    while(c <= '9' && c >= '0')x = x * 10 + c - '0',c=  getchar(); 
    return x * f; 
} 
const int maxn = 100007; 
int n ,block,fa[maxn],siz[maxn],son[maxn],num = 0,a[maxn],out[maxn]; 
vector<int>v[maxn]; 
int dfn[maxn]; 
void dfs(int x,int f) { 
    fa[x] = f; siz[x] = 1; 
    dfn[x] = ++ num; 
    for(int i = 0;i < v[x].size();++ i) { 
        int V = v[x][i]; 
        if(siz[V]) continue; 
        dfs(V,x); 
        siz[x] += siz[V]; 
        if(siz[V] > siz[son[x]]) son[x] = V; 
    } 
} 
int happen[maxn],belong[maxn]; 
int ans = 0,totq = 0; 

struct Query { 
	int l,r,id,ans; 
	Query(int L = 0,int R = 0,int Id = 0,int Ans = 0): l(L) , r(R), id(Id),ans(Ans) {}; 
	bool operator < (const Query &a) const { 
		return belong[l] == belong[a.l] ? r < a.r : belong[l] < belong[a.l]; 
	} 
}q[maxn]; 
 
void delet(int x) { 
    if(-- happen[x] == 0) ans --; 
} 
void add(int x) { 
    if(++ happen[x] == 1) ans ++; 
} 
void mo() { 
    sort(q + 1,q + totq + 1); 
    int l = 1,r = 0,fuck = 0; 
    for(int i = 1;i <= totq;++ i) { 
        while(l < q[i].l) delet(a[l ++]); 
        while(l > q[i].l) add(a[-- l]); 
        while(r < q[i].r) add(a[++ r]); 
        while(r > q[i].r) delet(a[r --]); 
        q[i].ans = ans; 
    } 
    for(int i = 1;i <= totq;++ i) 
    out[q[i].id] = q[i].ans; 
} 
int que,ask[maxn];  
void dealask() { 
    que = read(); 
    for(int i = 1;i <= que;++ i) { 
        ask[i] = read(); 
        for(int j = 0;j < v[ask[i]].size();++ j) { 
            int V = v[ask[i]][j]; 
            if(V == fa[ask[i]]) continue; 
            q[++ totq] = Query(dfn[V],dfn[V] + siz[V] - 1,V,0); 	
        } 	
    } 
} 
int data[maxn]; 
int main() { 
    n = read(); 
    block = sqrt(n); 
    for(int i = 1;i <= n;++ i) a[i] = data[i] = read(), belong[i] = i / block + 1; 
    sort(data + 1,data + n + 1); 
    num = unique(data + 1,data + n + 1) - data - 1; 
    for(int i = 1;i <= n;++ i) a[i] = lower_bound(data + 1,data + num + 1,a[i]) - data; 
    for(int u,V,i = 1;i < n;++ i) { 
        u = read(),V = read() ; 
        v[u].push_back(V);
		v[V].push_back(u); 
    }	 
    num = 0; 
    dfs(1,0); 
    dealask(); 
    mo(); 
	for(int i = 1;i <= que;++ i) { 
		int mx = 0,id = 0; 
		for(int j = 0 ;j < v[ask[i]].size(); ++ j) {
			int to = v[ask[i]][j]; 
			if(to == fa[ask[i]]) continue; 
			if(out[to] > mx || (siz[to] > siz[id] && out[to] == mx)) mx = out[to]; 
		
		} 	printf("%d\n",siz[id]); 
	}  
	return 0; 
} 
posted @ 2018-07-29 21:58  zzzzx  阅读(872)  评论(0编辑  收藏  举报