题解 (by;zjvarphi)
一道凸包的题
设 ( m dep_u) 表示节点 (u) 的深度,那么原式就可化为 (-frac{c_v-c_u}{dep_v-dep_u}) 这个式子可以维护一个下凸包
但是递归弹栈的话会被卡成 (n^2),所以我们可以写一个可持久化栈,或者是倍增跳栈
对于一个新加入的节点,我们对比它和不同祖先的斜率,如果有一个祖先 (fa),( m slope(x,fa)le slope(x,fa[fa])),那么就说明,我们要把 (fa) 这里的栈跳掉
Code
#include<bits/stdc++.h>
#define ri register signed
#define p(i) ++i
using namespace std;
namespace IO{
char buf[1<<21],*p1=buf,*p2=buf;
#define gc() p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++
template<typename T>inline void read(T &x) {
ri f=1;x=0;register char ch=gc();
while(ch<'0'||ch>'9') {if (ch=='-') f=0;ch=gc();}
while(ch>='0'&&ch<='9') {x=(x<<1)+(x<<3)+(ch^48);ch=gc();}
x=f?x:-x;
}
}
using IO::read;
namespace nanfeng{
#define FI FILE *IN
#define FO FILE *OUT
template<typename T>inline T cmax(T x,T y) {return x>y?x:y;}
template<typename T>inline T cmin(T x,T y) {return x>y?y:x;}
typedef double db;
static const int N=5e5+7;
int dep[N],c[N],first[N],fa[N][20],ch[N],n,t=1;
struct edge{int v,nxt;}e[N];
inline void add(int u,int v) {e[t].v=v,e[t].nxt=first[u],first[u]=t++;}
inline db calc(int x,int y) {return (1.0*(c[y]-c[x]))/(1.0*(dep[x]-dep[y]));}
void dfs(int x) {
ri ft=fa[x][0];
for (ri i(19);~i;--i) {
if (fa[ft][i]<=1) continue;
if (calc(x,fa[fa[ft][i]][0])<=calc(x,fa[ft][i])) ft=fa[fa[ft][i]][0];
}
if (ft>1&&calc(x,fa[ft][0])<=calc(x,ft)) ft=fa[ft][0];
ch[x]=fa[x][0]=ft;
for (ri i(1);i<=19;p(i)) fa[x][i]=fa[fa[x][i-1]][i-1];
for (ri i(first[x]),v;i;i=e[i].nxt) dep[v=e[i].v]=dep[x]+1,dfs(v);
}
inline int main() {
// FI=freopen("nanfeng.in","r",stdin);
// FO=freopen("nanfeng.out","w",stdout);
read(n);
for (ri i(1);i<=n;p(i)) read(c[i]);
for (ri i(2),u;i<=n;p(i)) read(u),add(fa[i][0]=u,i);
dfs(1);
for (ri i(2);i<=n;p(i)) printf("%.10lf
",calc(i,ch[i]));
return 0;
}
}
int main() {return nanfeng::main();}