I. Distance
time limit per test
6.0 s
memory limit per test
1024 MB
input
standard input
output
standard output
There are nn points on a horizontal line, labelled with 11 through nn from left to right.
The distance between the ii-th point and the (i+1)(i+1)-th point is aiai.
For each integer kk ranged from 11 to nn, you are asked to select exactly kk 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 TT indicating the number of test cases which is up to 10001000.
For each test case, the first line contains an integer nn indicating the number of points, where 2≤n≤1052≤n≤105.
The second line contains (n−1)(n−1) positive integers a1,a2,⋯,an−1a1,a2,⋯,an−1, where 1≤ai≤1041≤ai≤104.
We guarantee that the sum of nn in all test cases is up to 106106.
Output
For each test case, output a line containing nn integers, the ii-th of which is the maximum sum of distances in case k=ik=i. You should output exactly one whitespace between every two adjacent numbers and avoid any trailing whitespace in this line.
题意:给出n个点间的距离,依次求出取1~n个点所取点的最大距离。
思路:每次先左后右依此取点即可得到最大距离,取奇数个点的距离贡献等于上一个点,偶数个等于上一个点的贡献加上两点间的距离。
代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxx=1e6+7;
ll a[maxx],sum[maxx];
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
ll last=0,ans=0;//last上一个点的贡献
memset(a,0,sizeof a);
scanf("%d",&n);
for(int i=1;i<n;i++)
{
scanf("%I64d",&a[i]);
sum[i]=sum[i-1]+a[i];//前缀和
}
for(int i=1;i<=n;i++)
{
if(i%2==0)//偶数等于上一个点的贡献与上一个点距离之和
last+=(sum[n-i/2]-sum[i/2-1]);
ans+=last;
if(i!=n) printf("%I64d ",ans);
}
printf("%I64d\n",ans);//必须要long long
}
}