P3241 [HNOI2015]开店 题解


题面

这个题没有修改操作,所以不需要开线段树。跟平常的动态点分治做法一样,每个点开两个 vector 按照 \(x_i\) 排序存储到这个点和到这个点在点分树父亲的距离。每次找一个点的时候,暴力跳点分树父亲,直接在 vector 上二分查找满足 \([l,r]\) 这个区间的点和距离,直接计算即可。

点击查看代码
const int N=1.5e5+13,logN=21;
struct Edge{int v,w,nxt;}e[N<<1];
int n,m,q,a[N],h[N],etot;
int siz[N],maxx[N],rt,psum,fa[N],dep[N];
ll dis[N][logN];
bool vis[N];
std::vector d[N],ch[N];
std::vector sd[N],sch[N];
inline void add_edge(int u,int v,int w){e[++etot]=(Edge){v,w,h[u]};h[u]=etot;}

namespace Tree{
int fa[N],dep[N],siz[N],son[N],top[N];ll dis[N];
void dfs1(int u,int f,int deep){
	dep[u]=deep,siz[u]=1,fa[u]=f;
	for(int i=h[u];i;i=e[i].nxt){
		int v=e[i].v;if(v==f) continue;
		dis[v]=dis[u]+e[i].w;
		dfs1(v,u,deep+1);
		siz[u]+=siz[v];
		if(siz[v]>siz[son[u]]) son[u]=v;
	}
}
void dfs2(int u,int topf){
	top[u]=topf;
	if(!son[u]) return;
	dfs2(son[u],topf);
	for(int i=h[u];i;i=e[i].nxt){
		int v=e[i].v;
		if(v!=fa[u]&&v!=son[u]) dfs2(v,v);
	}
}
inline void init(){dfs1(1,0,0);dfs2(1,1);}
inline int lca(int u,int v){
	while(top[u]!=top[v]){
		if(dep[top[u]]r) swap(l,r);pii tmpl=mp(l,-LLINF),tmpr=mp(r,LLINF);
		int L=std::lower_bound(ch[x].begin(),ch[x].end(),tmpl)-ch[x].begin();
		int R=std::lower_bound(ch[x].begin(),ch[x].end(),tmpr)-ch[x].begin()-1;
		ll ans=0;
		if(R>=0) ans=sch[x][R]-(L>0?sch[x][L-1]:0);
		for(int u=x;fa[u];u=fa[u]){
			L=std::lower_bound(ch[fa[u]].begin(),ch[fa[u]].end(),tmpl)-ch[fa[u]].begin();
			R=std::lower_bound(ch[fa[u]].begin(),ch[fa[u]].end(),tmpr)-ch[fa[u]].begin()-1;
			if(R>=0) ans+=sch[fa[u]][R]-(L>0?sch[fa[u]][L-1]:0)+(R-L+1)*dis[x][dep[x]-dep[fa[u]]];
			L=std::lower_bound(d[u].begin(),d[u].end(),tmpl)-d[u].begin();
			R=std::lower_bound(d[u].begin(),d[u].end(),tmpr)-d[u].begin()-1;
			if(R>=0) ans-=sd[u][R]-(L>0?sd[u][L-1]:0)+(R-L+1)*dis[x][dep[x]-dep[fa[u]]];
		}
		println(lastans=ans);
	}
	return 0;
}