# Bzoj4381 [poi2015]odwiedziny

## 根号分治的思想优化树剖

Posted by yjjr's blog on April 12, 2018 1 minutes to read

# 题目

## Description

Byteasar想要走遍这整棵树，他会按照某个1到n的全排列b走n-1次，第i次他会从b[i]点走到b[i+1]点，并且这一次的步伐大小为c[i]。

## Sample Input

5
1 2 3 4 5
1 2
2 3
3 4
3 5
4 1 5 2 3
1 3 1 1


## Sample Output

10
6
10
5


# code

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
using namespace std;
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=5e4+6;
int n,blo,cnt,dfsclk,a[maxn],b[maxn],fa[maxn],dep[maxn],sz[maxn],s[maxn][206],son[maxn],anc[maxn];
int pos[maxn],id[maxn],last[maxn];
struct edge{int to,next;}e[maxn<<1];
void insert(int u,int v){
e[++cnt]=(edge){v,last[u]};last[u]=cnt;
e[++cnt]=(edge){u,last[v]};last[v]=cnt;
}
inline int get_lca(int x,int y){
for(;anc[x]!=anc[y];x=fa[anc[x]])
if(dep[anc[x]]<dep[anc[y]])swap(x,y);
return (dep[x]<dep[y])?x:y;
}
inline int find(int x,int deep){
for(;dep[x]-dep[anc[x]]<deep;x=fa[anc[x]])deep-=dep[x]-dep[anc[x]]+1;
return id[pos[x]-deep];
}
void dfs(int x){
sz[x]=1;
for(int i=1,p=fa[x];i<=blo&&p;i++,p=fa[p])s[x][i]=s[p][i]+a[x];
reg(x){
if(e[i].to==fa[x])continue;
fa[e[i].to]=x;dep[e[i].to]=dep[x]+1;dfs(e[i].to);sz[x]+=sz[e[i].to];
if(sz[e[i].to]>sz[son[x]])son[x]=e[i].to;
}
}
void divide(int x,int tp){
anc[x]=tp;id[pos[x]=++dfsclk]=x;
if(son[x])divide(son[x],tp);
reg(x){
if(e[i].to==fa[x])continue;
if(e[i].to!=son[x])divide(e[i].to,e[i].to);
}
}
inline int query(int x,int y,int z){
if(z<=blo)return s[x][z]-s[y][z]+a[y];int i,sum=0;
for(;anc[x]!=anc[y];x=find(x,pos[x]-i))
for(i=pos[x];i>=pos[anc[x]];i-=z)sum+=a[id[i]];
for(int i=pos[x];i>=pos[y];i-=z)sum+=a[id[i]];
return sum;
}
inline int solve(int x,int y,int z){
int ans=0,lca=get_lca(x,y),len=dep[x]+dep[y]-(dep[lca]<<1);
if(len%z)ans+=a[y];y=find(y,len%z);
int t1=find(x,(dep[x]-dep[lca])/z*z);
if(dep[y]<=dep[lca])return ans+query(x,t1,z);
int t2=find(y,(dep[y]-dep[lca])/z*z);
if(t1==t2)ans-=a[t1];return ans+query(x,t1,z)+query(y,t2,z);
}
int main(){