SP10707 COT2 - Count on a tree II (树上莫队)

大概学了下树上莫队, 其实就是在欧拉序上跑莫队, 特判lca即可.

 

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(i,1,n) cout<<a[i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head




const int N = 1e5+10;
int n, m, a[N], b[N];
vector<int> g[N];
int fa[N], son[N], L[N], R[N], no[N];
int top[N], dep[N], sz[N];
int sqn, cnt, ans[N], blo[N], ff[N], vis[N];
struct _ {
	int l,r,lca,id;
	bool operator < (const _ & rhs) const {
		return blo[l]^blo[rhs.l]?l<rhs.l:blo[l]&1?r<rhs.r:r>rhs.r;
	}
} q[N];
void dfs(int x, int d, int f) {
	fa[x]=f,sz[x]=1,dep[x]=d,L[x]=++*L,no[*L]=x;
	for (int y:g[x]) if (y!=f) {
		dfs(y,d+1,x), sz[x]+=sz[y];
		if (sz[y]>sz[son[x]]) son[x]=y;
	}
	R[x]=++*L,no[*L]=x;
}
void dfs(int x, int tf) {
	top[x]=tf;
	if (son[x]) dfs(son[x],tf);
	for (int y:g[x]) if (!top[y]) dfs(y,y);
}
int lca(int x, int y) { 
	while (top[x]!=top[y]) {
		if (dep[top[x]]<dep[top[y]]) swap(x,y);
		x = fa[top[x]];
	}
	return dep[x]<dep[y]?x:y;
}
void add(int x) {
	if (vis[x]) {if (--ff[a[x]]==0) --cnt;}
	else {if (++ff[a[x]]==1) ++cnt;}
	vis[x] ^= 1;
}

int main() {
	scanf("%d%d", &n, &m), sqn=sqrt(n);
	REP(i,1,n) scanf("%d",a+i),b[i]=a[i];
	sort(b+1,b+1+n),*b=unique(b+1,b+1+n)-b-1;
	REP(i,1,n) a[i]=lower_bound(b+1,b+1+*b,a[i])-b;
	REP(i,1,2*n) blo[i]=i/sqn;
	REP(i,2,n) {
		int u, v;
		scanf("%d%d", &u, &v);
		g[u].pb(v),g[v].pb(u);
	}
	dfs(1,1,0),dfs(1,1);
	REP(i,1,m) {
		int x, y;
		scanf("%d%d", &x, &y);
		if (L[x]>L[y]) swap(x,y);
		int _lca = lca(x,y);
		if (_lca==x) q[i].l=L[x];
		else q[i].l=R[x],q[i].lca=_lca;
		q[i].id=i, q[i].r=L[y];
	}
	sort(q+1,q+1+m);
	int ql=1,qr=0;
	REP(i,1,m) {
		while (ql<q[i].l) add(no[ql++]);
		while (qr>q[i].r) add(no[qr--]);
		while (ql>q[i].l) add(no[--ql]);
		while (qr<q[i].r) add(no[++qr]);
		if (q[i].lca) add(q[i].lca);
		ans[q[i].id] = cnt;
		if (q[i].lca) add(q[i].lca);
	}
	REP(i,1,m) printf("%d\n", ans[i]);
}

 

posted @ 2019-04-02 09:50  uid001  阅读(367)  评论(0编辑  收藏  举报