Problem Description
PM Room defines a sequence A = {A
1, A
2,..., A
N}, each of which is either 0 or 1. In order to beat him, programmer Moor has to construct another sequence B = {B
1, B
2,... , B
N} of the same length, which satisfies that:
Input
The input consists of multiple test cases. The number of test cases T(T<=100) occurs in the first line of input.
For each test case:
The first line contains a single integer N (1<=N<=100000), which denotes the length of A and B.
The second line consists of N integers, where the ith denotes A i.
For each test case:
The first line contains a single integer N (1<=N<=100000), which denotes the length of A and B.
The second line consists of N integers, where the ith denotes A i.
Output
Output the minimal f (A, B) when B is optimal and round it to 6 decimals.
Sample Input
4 9 1 1 1 1 1 0 0 1 1 9 1 1 0 0 1 1 1 1 1 4 0 0 1 1 4 0 1 1 1
Sample Output
1.428571 1.000000 0.000000 0.000000
题目描述:
有两个几何A和B,他们长度一样,几何A要么是0要么是1,由输入给出,现在让你求一个非递减序列B,使得对(Ai-Bi)^2的和最小。输出最小值,长度n<=10,000。
当时这个题目是我读的,因为此前做完一个模拟退火的题目,在二维中找一个点到给定的n个点的距离和最小。我想到用此算法去分析下,发现,这是求多个点,难以找到相联系的。后来,队友发现时数学平均值的应用,对于A集合,前面的0和后面的1都可以除去,因为使得最小,他们的和为0,之后,序列A就变成了 1 0 1 1 0 1 0 0 1 1 0 0 0 这样的了,如果考虑分割,变成 1 0 这样的一份份,前面1后面0。按照这个案例,每一段取平均值,那么为 1/2 2/3 1/3 2/5为了满足非递减序列,就把 Bj <Bj-1 和并起来。
注意::这个题在写代码的时候不要想简化,简单暴力求解就行了。越简化越复杂。总之:要思路清晰。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#define rt return
#define sf scanf
#define pf printf
#define REP0(i,n) for(int i=0;i<(n);i++)
#define REP1(i,n) for(int i=1;i<=(n);i++)
#define REP(i,s,n) for(int i=s;i<=(n);i++)
#define db double
#define pb push_back
#define LL long long
#define INF 0x3fffffff
#define eps 1e-8
#define PI acos(-1)
#define maxn 100010
using namespace std;
int n;
int c[maxn];
struct node{
db a,b;
db val;
}p[maxn],q[maxn];
int main(){
#ifdef ACBang
freopen("in.txt","r",stdin);
#endif
int CAS;sf("%d",&CAS);
while(CAS--){
sf("%d",&n);
REP0(i,n)sf("%d",&c[i]);
int l=0,r=n-1;
while(c[l]==0)l++;
while(c[r]==1)r--;
int t=0;
while(l<r){
int cnt=0;
while(l<=r&&c[l]==1){cnt++;l++;}
p[t].a=cnt;
cnt=0;
while(l<=r&&c[l]==0){cnt++;l++;}
p[t].b=cnt;
p[t].val=p[t].a/(p[t].a+p[t].b);
t++;
}
// REP0(i,t)
// cout<<p[i].a<<" "<<p[i].b<<endl;
// cout<<endl;
if(t==0){pf("0.000000\n");continue;}
int z=-1;
q[++z]=p[0];
REP(i,1,t-1){
while(z>=0&&p[i].val < q[z].val ){
p[i].a+=q[z].a;
p[i].b+=q[z].b;
p[i].val=p[i].a/(p[i].a+p[i].b);
z--;
}
q[++z]=p[i];
}
db ans=0;
REP(i,0,z){
ans+=(q[i].val*q[i].val*q[i].b+(1-q[i].val)*(1-q[i].val)*q[i].a);
}
pf("%.6lf\n",ans);
}
rt 0;
}