题目链接:点击查看
题目大意:给出 n 个数字组成的序列,现在可以对数列进行多次操作,每次操作可以选择其中一段连续的数列,用其平均数替换原位置,换句话说,若原连续数列为 1 2 3,则可以替换为 2 2 2,问如何操作可以使得最后答案的字典序最小
题目分析:因为要使得字典序最小,我们可以在线操作,因为涉及到平均数,我们可以将数列分为几个不同的区块,每个区块的平均值都相同,对于每加入的一个新的数字 num ,若当前的 num 比最后一个区块的平均值要小,那么就说明如果将当前这个 num 与最后一个区块合并后,最后一个区块的平均值就会变小,相应的字典序也会变小,当然合并后倒数第二个区块也会受到影响,应该每次都向前尝试合并
但这样看起来是一个n*n的写法,但因为每次合并后的区块数都会减少一个,而初始时只有 n 个区块,这样累加后的时间复杂度实际上只有O(n)的
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e6+100;
const double eps = 1e-12;
int sgn(double x){
if(fabs(x) < eps)return 0;
if(x < 0)return -1;
else return 1;
}
struct Node
{
int len;
LL sum;
bool operator<(const Node& a)const
{
return sgn((1.0*sum/len)-(1.0*a.sum/a.len))<0;
}
}p[N];
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
//#endif
// ios::sync_with_stdio(false);
int n,pos=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
pos++;
scanf("%lld",&p[pos].sum);
p[pos].len=1;
while(pos>1&&p[pos]<p[pos-1])
{
p[pos-1].sum+=p[pos].sum;
p[pos-1].len+=p[pos].len;
pos--;
}
}
for(int i=1;i<=pos;i++)
for(int j=1;j<=p[i].len;j++)
printf("%.12f\n",1.0*p[i].sum/p[i].len);
return 0;
}