标签:putc cin fun type ace return ORC out after
https://codeforces.com/group/5yyKg9gx7m/contest/277016/problem/I
I. Bashar and Hamada
Bashar is a very smart person, he invented a new function F(S), where S is a multiset of integers.
The function F(S) returns the sum of the absolute difference between every pair of elements in S.
For example F({3,3,1,7}) = |3−3| + |3−1| + |3−7| + |3−1| + |3−7| + |1−7| = 18.
After that Bashar gave Hamada an array a that contains n integers, and asked him to solve this problem.
For every k such that (2≤k≤n), Hamada should choose a subsequence of k integers from a, such that F(S) is maximised.
Hamada couldn‘t solve the problem and he asked you for help.
Input
The first line of input contains one integer n (2≤n≤3×105) which is the size of array a.
The second line contains n integers, the ith one is ai (1≤ai≤108), which is the ith element in the array.
Output
For every k such that (2≤k≤n), print the maximum possible F(S) of a subsequence of size k, starting from k=2 ending at k=n.
Example
inputCopy
3
1 7 5
outputCopy
6 12
Note
a subsequence of size k is a sequnece that can be obtained be removing n−k integers from a.
分析:
首先选择2个数要值最大,就是令他们差最大,所以选最大最小值。
先看一个规律
比如{1,2,3,4,5,7},开始ans=0;
开始:ans+= |1-7|
插入5: ans+=|5-1|+|5-7|=|1-7|
插入2: ans+=|2-1|+|2-7|+|2-5|==|1-7|+|2-5|
插入4: ans+=|4-1|+|4-7|+|4-5|+|4-2|==|1-7|+|2-5|
插入3: ans+=|3-1|+|3-7|+|3-5|+|3-2|+|3-4|==|1-7|+|2-5|+|3-4|
这样列出来就很明显了。奇数次插入,要加的数保存不变。
可以看到每插入2个就增加一个组合,只要每次加入的组合为最大,就能保证答案最大。
每次组合都选差最大的,排序后,就是左右各一个。
代码:
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<sstream> #include<vector> #include<stack> #include<deque> #include<cmath> #include<map> using namespace std; typedef long long ll; const int maxn=3e5+6; ll a[maxn]; ll ans=0; int main() { int n; cin>>n; for(int i=1;i<=n;i++) { scanf("%lld",&a[i]); } sort(a+1,a+n+1); ans=a[n]-a[1]; printf("%lld ",ans); ll temp=ans; int k=n-1; int f=2; for(int i=1;i<n-1;i++) { if(i%2==0) temp+=a[k--]-a[f++]; ans+=temp; printf("%lld ",ans); } return 0; }
标签:putc cin fun type ace return ORC out after
原文地址:https://www.cnblogs.com/studyshare777/p/12766707.html