题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4923
Room and Moor
Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 742 Accepted Submission(s): 220
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:
![](https://i-blog.csdnimg.cn/blog_migrate/79bd70683dbeaf3d751b20c6d9463011.jpeg)
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
Author
BUPT
Source
Recommend
这道题,比赛时候没做出来,后面看了题解又想了好久才搞出来的。
对f(x)求导可以得到 在一段区间内,当x为平均值时,f(x)的值最小,但由于我们可以分成好多段,每一段的值可以是不同的。因此我们需要模拟一个栈来维护它。
从左到右进行扫描,遇到A[i],时把它加入栈内。然后检查栈顶是否有x[i]>x[i-1],若有则将其合并取平均值,为了方面我这边用num[i]表示第i个区间内1的数量,len[i]表示第i个段的长度。所以只需要判断 num[i]*len[i-1]>num[i-1]*len[i]的大小即可。
到最后,我们加上每个段的大小即可。需要注意的一点是num[i]统计的是第i段1的数量,那么len[i]-num[i] 统计的便是该段0的数量。将它们加起来即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<cstdlib>
#include<stack>
#include<queue>
#include<bitset>
using namespace std;
#define CLR(A) memset(A,0,sizeof(A))
const int MAX=100010;
double num[MAX];
double len[MAX];
int main(){
int T;
while(~scanf("%d",&T)){
while(T--){
int n,cnt=0;
CLR(num);CLR(len);
scanf("%d",&n);
for(int i=0;i<n;i++){
int v;scanf("%d",&v);
num[cnt]=v;
len[cnt]=1;
while(cnt>=1){
if(num[cnt]*len[cnt-1]>num[cnt-1]*len[cnt]) break;
num[cnt-1]+=num[cnt];
len[cnt-1]+=len[cnt];
cnt--;
}
cnt++;
}
double ret=0.0;
for(int i=0;i<cnt;i++){
double x=num[i]/len[i];
ret+=x*x*(len[i]-num[i])+(1-x)*(1-x)*num[i];
}
printf("%.6lf\n",ret);
}
}
return 0;
}