hdu 4923 Room and Moor--2014 Multi-University Training Contest 6

79 篇文章 0 订阅

题目链接: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:

 

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.
 

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
We have carefully selected several similar problems for you:   4929  4928  4926  4924  4922 
 

Statistic |  Submit |  Discuss |  Note


这道题,比赛时候没做出来,后面看了题解又想了好久才搞出来的。

对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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值