2020牛客暑期多校训练营(第三场)E——Two Matchings
题目描述
输入描述
The first line contains one integer t (1≤t≤5×10^4) --- the number of test cases.
Each test contains two lines. The first line contains one integer n (n≥4n \ge 4n≥4 and n is even), The second line contains n integers a1,a2,…,an (0≤ai≤10^9).
The sum of n across the test cases doesn't exceed 2×10^5.
输出描述
For each test, output one line which contains only one integer representing the answer of this test.
输入
2
4
0 8 0 0
6
3 1 4 1 5 9
输出
16
16
说明
In the first test, one possible combinable matchings with the minimum sum of cost are [2,1,4,3] and [4,3,2,1]. The cost of the first matching is (|0-8|+|8-0|+|0-0|+|0-0|)/2=8, the cost of the second matching is (|0-0|+|8-0|+|0-8|+|0-0|)/2=8.So their sum is 8+8=16.
题目大意
题解
我们可以通过排序,之后更方便匹配,同时以++--(长度为4时)++-+--(长度为6时)最优,之后可以使用dp求值。
AC代码
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include<bits/stdc++.h>
#define INF 1ll<<60
using namespace std;
long long a[202020],dp[202020];
int main()
{
long long ans,T,n;
scanf("%lld",&T);
while(T--)
{
scanf("%lld",&n);
ans=0;
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
sort(a+1,a+1+n);
for(int i=2;i<=n;i+=2) ans+=a[i]-a[i-1];
dp[2]=INF;
dp[4]=a[4]+a[3]-a[2]-a[1];
dp[6]=a[6]+a[5]-a[4]+a[3]-a[2]-a[1];
for(int i=8;i<=n;i+=2)
dp[i]=min(dp[i-4]+a[i]+a[i-1]-a[i-2]-a[i-3],dp[i-6]+a[i]+a[i-1]-a[i-2]+a[i-3]-a[i-4]-a[i-5]);
printf("%lld\n",ans+dp[n]);
}
}