码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4923 Room and Moor

时间:2017-05-01 09:51:01      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:组成   nbsp   return   multiple   turn   tmp   esc   als   occurs   


Problem Description
PM Room defines a sequence A = {A1, A2,..., AN}, each of which is either 0 or 1. In order to beat him, programmer Moor has to construct another sequence B = {B1, B2,... , BN} 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 Ai.
 

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序列由0,1组成。然后让你找一个等长的B序列使得相应数差的平方和是最小的

思路:最后得到的数列的形如{x1, x1, x2, x2 ..... xn, xn},且{x1 < x2 < ... < xn}。首先我们能够得到某段区间[xl, xl+1, .. xr]和是

∑(xl, xr) (xi-x)^2, 我们能够知道他是一个形如:ax^2+bx+c 的函数,所以我们能够得到最小值的x是这个区间数的平均值,
我们将过程模拟成栈,那么扫描入栈一个我们就推断它求的x与栈顶的值时候满足非递减的关系。不是的话我们合并。处理完后求值即可了

num[i]表示该区间1的个数,len[i]表示该区间的长度

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100005;

double num[maxn], len[maxn];

int main() {
	int t, n;
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);		
		int cnt = 0, a;
		for (int i = 0; i < n; i++) {
			scanf("%d", &a);	
			num[cnt] = a;
			len[cnt++] = 1;
			while (cnt >= 2) {
				if (num[cnt-1]/len[cnt-1] > num[cnt-2]/len[cnt-2])
					break;
				num[cnt-2] += num[cnt-1];
				len[cnt-2] += len[cnt-1];
				cnt--;
			}
		}
		double ans = 0.0;
		for (int i = 0; i < cnt; i++) {
			double tmp = num[i]/len[i];
			ans += tmp*tmp*(len[i]-num[i]) + (1-tmp)*(1-tmp)*num[i];
		}
		printf("%.6lf\n", ans);
	}
	return 0;
}



HDU 4923 Room and Moor

标签:组成   nbsp   return   multiple   turn   tmp   esc   als   occurs   

原文地址:http://www.cnblogs.com/cxchanpin/p/6791197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!