I. Distance

题目链接
There are n points on a horizontal line, labelled with 1 through n from left to right.

The distance between the i-th point and the (i+1)-th point is ai.

For each integer k ranged from 1 to n, you are asked to select exactly k different given points on the line to maximize the sum of distances between all pairs of selected points.

Input
The input contains several test cases, and the first line contains a positive integer T indicating the number of test cases which is up to 1000.

For each test case, the first line contains an integer n indicating the number of points, where 2≤n≤105.

The second line contains (n−1) positive integers a1,a2,⋯,an−1, where 1≤ai≤104.

We guarantee that the sum of n in all test cases is up to 106.

Output
For each test case, output a line containing n integers, the i-th of which is the maximum sum of distances in case k=i. You should output exactly one whitespace between every two adjacent numbers and avoid any trailing whitespace in this line.

input
1
5
2 3 1 4

output
0 10 20 34 48

Note
The figure below describes the sample test case.

在这里插入图片描述

The only best selection for k=2 should choose the leftmost and the rightmost points, while a possible best selection for k=3 could contain any extra point in the middle.

题解:
数轴上n个点,对每个k=1,2,……,n,选出恰好k个点使两两距离值和最大
显然一次选择最左最右点

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
LL t,n,l,r,cur,k,a[N],ans[N];//long long 类型,因为计算的是任意两个点之间的距离
int main(){
	ios :: sync_with_stdio(false);
	cin.tie(0);
	while(cin >> t){
		while(t--){
			cin >> n;
			a[1] = 0;
			for(int i = 2;i <= n;i++){
				cin >> a[i];
				a[i] += a[i - 1];//计算每个点的距离
			}
			l = 2,r = n - 1,k = 3,ans[1] = 0,ans[2] = cur = a[n];
			for(int i = 3;i <= n;i++){
				if(i & 1){
					ans[k] = ans[k - 1] + cur;
					k++;
				}
				else{
					cur += a[r] - a[l];
					ans[k] = ans[k - 1] + cur;
					l++,r--,k++;
				}
			}
			for(int i = 1;i < k;i++){
                if(i == 1) 
					cout << ans[i];
                else 
					cout << " " << ans[i];
			}
			cout << endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值