首页 > 其他 > 详细

HDU 4923 Room and Moor

时间:2014-08-07 23:18:55      阅读:422      评论:0      收藏:0      [点我收藏+]

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:

bubuko.com,布布扣
 

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,布布扣,bubuko.com

HDU 4923 Room and Moor

原文:http://blog.csdn.net/u011345136/article/details/38424541

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!