多明显的斜率式然而我没有看出来
然而不管是我乱搞的思路还是正解的凸包思路都需要一个可持久化栈
考场上想到可持久化单调栈,但不会实现……
其实单调栈不管是否可持久化都能倍增弹栈
但普通单调栈本来就O(n)的倍增弹栈也没啥用
- 可持久化单调栈/队列注意要倍增处理
这里涉及求凸包切线
如果是个普通单调栈维护的凸包直接三分求就行
但这里的可持久化单调栈是倍增维护的,不好三分
所以考虑如何判断当前枚举到的点在最终答案点的哪一侧
如果我们要check一个点v,发现在答案左侧有calc(u, fa(v))>calc(u, v),而答案右侧有calc(u, fa(v))<calc(u, v)
就可以二分了 其实普通单调栈也可以这样避免三分
完全想不到……
Code:
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 1000100
#define ll long long
#define ld long double
#define usd unsigned
#define ull unsigned long long
#define double long double
//#define int long long
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
char buf[1<<21], *p1=buf, *p2=buf;
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n;
int head[N], size;
double c[N];
struct edge{int to, next;}e[N<<1];
inline void add(int s, int t) {edge* k=&e[++size]; k->to=t; k->next=head[s]; head[s]=size;}
namespace force{
double ans[N];
void dfs(int u, double cv, int dis) {
if (dis) ans[u] = min(ans[u], (cv-c[u])/(1.0*dis));
for (int i=head[u]; i; i=e[i].next) dfs(e[i].to, cv, dis+1);
}
void solve() {
for (int i=1; i<=n; ++i) ans[i]=1e30;
for (int i=1; i<=n; ++i) dfs(i, c[i], 0);
for (int i=2; i<=n; ++i) printf("%.10Lf\n", ans[i]);
exit(0);
}
}
namespace task{
//struct que{double c, d, k; inline void build(double c_, double d_, double k_){c=c_; d=d_; k=k_;}}sta[N][25];
int sta[N][25];
double ans[N], dep[N], reck[N];
inline double calc(int u, int v) {return (c[u]-c[v])/(dep[u]-dep[v]);}
void dfs(int u) {
//cout<<"dfs "<<u<<endl;
//cout<<"P: "<<dep[u]<<' '<<c[u]<<endl;
for (int i=1; i<=22; ++i)
if (dep[u]>=(1<<i)) sta[u][i]=sta[sta[u][i-1]][i-1];
else break;
//cout<<"sta: "; for (int t=sta[u][0]; t; t=sta[t][0]) cout<<t<<' '; cout<<endl;
if (u!=1) {
int now=u;
for (int i=22; i>=0; --i)
if (sta[sta[now][i]][0] && calc(u, sta[now][i])<calc(u, sta[sta[now][i]][0])) now=sta[now][i]; // cout<<"now: "<<now<<endl;
//while (sta[now][0] && calc(u, sta[now][0])>=k) {k=calc(u, sta[now][0]); now=sta[now][0];} //cout<<"now: "<<now<<' '<<k<<endl;
if (sta[now][0]) now=sta[now][0];
ans[u]=calc(u, now);
//cout<<"choose: "<<now<<endl;
sta[u][0]=now;
}
for (int i=1; i<=22; ++i)
if (dep[u]>=(1<<i)) sta[u][i]=sta[sta[u][i-1]][i-1];
else break;
for (int i=head[u],v; i; i=e[i].next) {
v = e[i].to;
dep[v]=dep[u]+1; sta[v][0]=u;
dfs(v);
}
//cout<<"return "<<endl;
}
void solve() {
dep[1]=1;
dfs(1);
for (int i=2; i<=n; ++i) printf("%.10Lf\n", -1.0*ans[i]);
exit(0);
}
}
signed main()
{
#ifdef DEBUG
freopen("1.in", "r", stdin);
#endif
n=read();
for (int i=1; i<=n; ++i) c[i]=read();
for (int i=2; i<=n; ++i) add(read(), i);
//force::solve();
task::solve();
return 0;
}