求调,树上莫队WA

SP10707 COT2 - Count on a tree II

代码在二楼 ```c #include<bits/stdc++.h> using namespace std; const int N=200010; map<int,int> mp; vector<int> e[N]; int us[N],vis[N],a[N],cnt,dep[N],bel[N],tot,n,m,bl,st[N],l=1,r,ed[N],t,f[N][20],ans[N],xu,ou[N],T,L[N],R[N]; struct query{ int l,r,id,op,lc; bool operator<(const query&b)const{ if(bel[l]!=bel[b.l]) return l<b.l; return r<b.r; } }q[N]; void dfs(int x,int fa,int dp){ dep[x]=dp; f[x][0]=fa; ou[++xu]=x; st[x]=xu; for(int y:e[x]){ if(y==fa) continue; dfs(y,x,dp+1); } ou[++xu]=x; ed[x]=xu; } void initf(){ for(int x=1;x<=n;x++){ for(int i=1;i<=19;i++){ f[x][i]=f[f[x][i-1]][i-1]; } } } int lca(int x,int y){ if(dep[x]<dep[y]) swap(x,y); for(int i=19;i>=0;i--){ if((dep[x]-dep[y])>=(1<<i)){ x=f[x][i]; } } if(x==y) return x; for(int i=19;i>=0;i--){ if(f[x][i]!=f[y][i]){ x=f[x][i]; y=f[y][i]; } } return f[x][0]; } void add(int x){ if(vis[a[ou[x]]]==0) tot++; vis[a[ou[x]]]++; } void del(int x){ if(vis[a[ou[x]]]==1) tot--; vis[a[ou[x]]]--; } void ch(int x){ if(us[ou[x]]==0) add(x); else del(x); us[ou[x]]^=1; } signed main(){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>a[i]; if(mp[a[i]]==0) mp[a[i]]=++cnt; a[i]=mp[a[i]]; } for(int i=1;i<n;i++){ int x,y; cin>>x>>y; e[x].push_back(y); e[y].push_back(x); } for(int i=1;i<=m;i++){ cin>>q[i].l>>q[i].r; q[i].id=i; } dfs(1,0,1); initf(); for(int i=1;i<=m;i++){ int lc=lca(q[i].l,q[i].r); if(lc==q[i].l||lc==q[i].r){ int stl=st[q[i].l],str=st[q[i].r]; q[i].l=min(stl,str); q[i].r=max(stl,str); q[i].op=0; }else{ int ll=ed[q[i].l],rr=st[q[i].r]; int lll=ed[q[i].r],rrr=st[q[i].l]; if(ll<rr){ q[i].l=ll,q[i].r=rr; }else{ q[i].l=lll,q[i].r=rrr; } q[i].op=1; } q[i].lc=lc; } n*=2; bl=pow(n,0.5); for(int i=1;i<=n;i+=bl){ L[++T]=i; R[T]=i+bl-1; if(R[T]>n) R[T]=n; } for(int i=1;i<=T;i++){ for(int j=L[i];j<=R[i];j++){ bel[j]=i; } } sort(q+1,q+m+1); for(int i=1;i<=m;i++){ while(l>q[i].l) ch(--l); while(l<q[i].l) ch(l++); while(r<q[i].r) ch(++r); while(r>q[i].r) ch(r--); int tmp=tot; if(q[i].op==1){ if(vis[a[q[i].lc]]==0) tmp++; } ans[q[i].id]=tmp; } for(int i=1;i<=m;i++){ cout<<ans[i]<<endl; } return 0; } ```
by Jie_Xu_Sheng @ 2023-03-14 22:55:08


虽然我没看完代码,但是我猜你某个地方把序列编号和欧拉序编号弄错了
by unputdownable @ 2023-03-15 06:56:47


|