xlsfyc @ 2022-05-22 14:34:31
rt,主席树写法,代码如下:
#include<bits/stdc++.h>
#define mid (l+r)/2
using namespace std;
int n,q,head[300001]={0},fa[300001]={0},d[300001]={0},size[300001]={0},dfn[300001]={0},rt[300001]={0},tot=1,opt=0,cnt=0;
struct Edge{
int to,nxt;
}e[600001];
struct Node{
int lc,rc;
long long ans;
}tree[6000001];
void add(int x,int y){
e[++opt].to=y;
e[opt].nxt=head[x];
head[x]=opt;
}
void dfs1(int x,int f){
size[x]=1;
for(int i=head[x];i;i=e[i].nxt){
int v=e[i].to;
if(v==f) continue;
tot=max(tot,d[v]=d[x]+1),fa[v]=x;//注释这行后就不MLE了
dfs1(v,x),size[x]+=size[v];
}
}
void insert(int &i,int l,int r,int k,int val){
Node t=tree[i];
tree[i=++cnt]=t,tree[i].ans+=val;
if(l==r) return;
if(k<=mid) insert(tree[i].lc,l,mid,k,val);
else insert(tree[i].rc,mid+1,r,k,val);
}
void dfs2(int x){
dfn[x]=++opt,rt[opt]=rt[opt-1];
insert(rt[opt],1,tot,d[x],size[x]-1);
for(int i=head[x];i;i=e[i].nxt){
int v=e[i].to;
if(v==fa[x]) continue;
dfs2(v);
}
}
long long query(int i,int j,int l,int r,int L,int R){
if(l==L && r==R) return tree[j].ans-tree[i].ans;
long long ans=0;
if(L<=mid) ans+=query(tree[i].lc,tree[j].lc,l,mid,L,R);
if(R>mid) ans+=query(tree[i].rc,tree[j].rc,mid+1,r,L,R);
return ans;
}
int main(){
scanf("%d%d",&n,&q);
for(int i=1;i<=n-1;i++){
int x,y;
scanf("%d%d",&x,&y);
add(x,y),add(y,x);
}
d[1]=1,dfs1(1,1);
opt=0,dfs2(1);
while(q--){
int p,k;
scanf("%d%d",&p,&k);
if(d[p]==tot) printf("0\n");
else printf("%lld\n",(long long)min(k,d[p]-1)*(size[p]-1)+query(rt[dfn[p]-1],rt[dfn[p]+size[p]-1],1,tot,d[p]+1,min(tot,d[p]+k)));
}
return 0;
}
by Keep_RAD @ 2022-05-22 14:53:00
@sid666
d[v]=d[x];
tot=max(tot,d[x]+1),fa[v]=x;
这样是wa了
by xlsfyc @ 2022-05-23 13:08:38
@run_after_dream 我知道啊。但是本身深度就是要加一的,这样子肯定会 wa 啊。所以您知道正解为什么会MLE么?
by xlsfyc @ 2022-05-23 13:09:27
换句话说,您说了和没说一样
by xlsfyc @ 2022-06-05 09:45:00
QAQ,在线等
by lpz2020 @ 2022-07-17 19:45:48
我也是