E - Water Balance
https://codeforces.com/contest/1300/problem/E
outputstandard output
There are n water tanks in a row, i-th of them contains ai liters of water. The tanks are numbered from 1 to n from left to right.
You can perform the following operation: choose some subsegment [l,r] (1≤l≤r≤n), and redistribute water in tanks l,l+1,…,r evenly. In other words, replace each of al,al+1,…,ar by al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7] you choose l=2,r=3, new volumes of water will be [1,4.5,4.5,7]. You can perform this operation any number of times.
What is the lexicographically smallest sequence of volumes of water that you can achieve?
As a reminder:
A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b.
思路:首先肯定是前面的数越小越好,假设l ~ r的均值为x1,l ~ r1的均值为x2,如果x2 < x1,可以证明对l ~ k进行一次操作后字典序会变小(直接列个不等式解一下就好)
即每加入一个数,和上一块的均值比较一下大小,比它小的话就跟上一块合并,不断循环下去,类似单调栈的操作
#include<bits/stdc++.h>
#define MAXN 1000005
using namespace std;
double a[MAXN],sum[MAXN],st[MAXN];
int n,l[MAXN],r[MAXN],cnt;
int main()
{
scanf("%d",&n);
sum[0] = 0;
for(int i = 1;i <= n;++i)
{
scanf("%lf",&a[i]);
sum[i] = sum[i-1] + a[i];
}
cnt = 0;
st[0] = 0;
for(int i = 1;i <= n;++i)
{
double tmp = a[i];
int ll = i;
while(cnt && tmp <= st[cnt])
{
ll = l[cnt];
tmp = (sum[i] - sum[ll-1]) / (i - ll + 1);
--cnt;
}
st[++cnt] = tmp;
l[cnt] = ll;
r[cnt] = i;
}
for(int i = 1;i <= cnt;++i)
{
for(int j = l[i];j <= r[i];++j)
printf("%.10lf\n",st[i]);
}
return 0;
}