CF375 D. Tree and Queries


题目传送门:https://codeforces.com/problemset/problem/375/D

题目大意:
给定一个\(n\)个节点的树,每个节点有颜色\(C_x\),给定\(m\)组询问,每次询问\(v_i\)及其子树内,出现次数\(\geqslant k_i\)的颜色种数


首先给树上节点打上Dfs序,这样树上询问便可以转化为区间询问

由于没有牵涉到修改,因此我们考虑莫队

每次需要统计次数\(\geqslant k_i\)的颜色种数,故我们用树状数组维护

理论时间复杂度\(O(n\sqrt n \log_2n)\),但常数很小,因为莫队跑不满

/*program from Wolfycz*/
#include
#include
#include
#include
#include
#include
#include
#define Fi first
#define Se second
#define ll_inf 1e18
#define MK make_pair
#define sqr(x) ((x)*(x))
#define pii pair
#define int_inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
templateinline T frd(T x){
	int f=1; char ch=gc();
	for (;ch<'0'||ch>'9';ch=gc())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=gc())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
templateinline T read(T x){
	int f=1; char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x<0)	putchar('-'),x=-x;
	if (x>9)	print(x/10);
	putchar(x%10+'0');
}
const int N=1e5;
int pre[(N<<1)+10],now[N+10],child[(N<<1)+10],DFN[N+10],FND[N+10],Sz[N+10];
int Time,tot;
void join(int x,int y){pre[++tot]=now[x],now[x]=tot,child[tot]=y;}
void insert(int x,int y){join(x,y),join(y,x);}
void Dfs(int x,int fa){
	FND[DFN[x]=++Time]=x,Sz[x]++;
	for (int p=now[x];p;p=pre[p]){
		int son=child[p];
		if (son==fa)	continue;
		Dfs(son,x),Sz[x]+=Sz[son];
	}
}
int pos[N+10],C[N+10],Cnt[N+10],Ans[N+10];
struct node{
	int l,r,K,ID;
	node(int _l=0,int _r=0,int _K=0,int _ID=0){l=_l,r=_r,K=_K,ID=_ID;}
	bool operator <(const node &tis)const{return pos[l]!=pos[tis.l]?ln?0:TA.Query(T(K));}
#undef T
int main(){
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	n=read(0),m=read(0),len=sqrt(n);
	for (int i=1;i<=n;i++)	C[i]=read(0),pos[i]=(i-1)/len+1;
	for (int i=1;iAsk[i].r)	Add(r--,-1);
		while (lAsk[i].l)	Add(--l, 1);
		Ans[Ask[i].ID]=Query(Ask[i].K);
	}
	for (int i=1;i<=m;i++)	printf("%d\n",Ans[i]);
	return 0;
}

相关