The third E-Two Matching of 2020 Summer Niuke Multi-school

The title here is the
meaning of the title: Given an array, what is the sum of the minimum and the second smallest value that satisfy the arrangement?
Idea:
Write a sequence of length 4 and you can see that the minimum is two-by-two after sorting Add, and the second smallest value is to move the first element to the last, and then subtract two by two to get the second smallest value.
We first calculate the length as 4, after calculating the length as 6, and after calculating the length as 8, we can find that any even number can have these three values ​​recursively, because n is an even number. At the same time, note that there is an option of dividing into 2 in this question. For the length of 8, whether to use one 8 or two fours, after writing it, the value obtained by two fours will be smaller, so I can use dp To solve this problem.

Code:

#include <bits/stdc++.h>
 
using namespace std;
typedef long long ll;
const int MAXN = 2e5+7;
ll a[MAXN],dp[MAXN];
 
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--){
    
    
        int n;
        scanf("%d",&n);
        for(int i = 1;i <= n;i ++){
    
    
            scanf("%lld",&a[i]);
        }
        ll ans = 0;
        sort(a+1,a+1+n);
        for(int i = 2;i <= n;i += 2){
    
    //先做的是最优解
            ans += (a[i]-a[i-1]);
        }
        //再开始解决次有解问题
        //没有dp2这种组合因此 dp6 也就没有dp4和dp2 dp8也只有两个dp4, 比较一下会得到单个dp8会小于两个dp4
        if(n>=4)dp[4] = a[3]-a[2]+a[4]-a[1];
        if(n>=6)dp[6] = a[3]-a[2]+a[5]-a[4]+a[6]-a[1];
        if(n>=8)dp[8] = a[3]-a[2]+a[4]-a[1]+a[7]-a[6]+a[8]-a[5];
        //因为 保证了n是偶数的 因此只需要现找出dp2,4,8 后面都可推得
        for(int i = 10;i <= n;i +=2){
    
    
            dp[i] = min(dp[i-4]+a[i]-a[i-3]+a[i-1]-a[i-2],
                dp[i-6]+a[i]-a[i-5]+a[i-1]-a[i-2]+a[i-3]-a[i-4]);
        }
        ans += dp[n];
        printf("%lld\n",ans);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45672411/article/details/107699561