2020牛客暑期多校第三场 E - Two Matchings(思维/dp)

题目链接


首先这个匹配的含义让我思考了好久,其实这个不关心序列具体的值,而是下标,假设一开始下标是 1   2   3   4   5   6 1~2~3~4~5~6 ,那么一个匹配可以是 4   3   2   1   6   5 4~3~2~1~6~5 ,这样对于交换的 1 , 4 1,4 来说, p p 1 = 1 , p p 4 = 1 p_{p_1}=1,p_{p_4}=1 ,然后就能理解匹配的意义了

最小值显然容易找到,就是排序后两两相减,但是次小值就很麻烦了,我是看第一篇题解讲的理解的,自认为讲不了那么好

n 10 n \geq 10 时,即可以将整个串分解成多个 4 r o t a t i o n 4-rotation 和多个 6 r o t a t i o n 6-rotation 组成。

那么得到了 d p dp 的递推公式:

d p [ i ] = m i n ( d p [ i 4 ] + v [ i 1 ] v [ i 4 ] , d p [ i 6 ] + v [ i 1 ] v [ i 6 ] ) dp[i] = min(dp[i-4]+v[i-1]-v[i-4], dp[i-6]+v[i-1]-v[i-6])

长度为4和6的预处理,长度为8的特判

#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define Vector Point
#define lowbit(x) (x&(-x))
#define mkp(x,y) make_pair(x,y)
#define mem(a,x) memset(a,x,sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const double dinf=1e300;
const ll INF=1e18;
const int Mod=1e9+7;
const int maxn=2e5+10;

ll d[maxn];
vector<int> a;

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    //ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int t,n;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        a.clear();
        for(int i=0,x;i<n;i++){
            scanf("%d",&x);
            a.push_back(x);
        }
        sort(a.begin(),a.end());
        d[0]=0;
        d[4]=a[3]-a[0];
        if(n==4){
            printf("%lld\n",d[n]*2);
            continue;
        }
        d[6]=a[5]-a[0];
        if(n==6){
            printf("%lld\n",d[n]*2);
            continue;
        }
        d[8]=a[7]-a[4]+d[4];
        if(n==8){
            printf("%lld\n",d[n]*2);
            continue;
        }
        for(int i=10;i<=n;i++)
            d[i]=min(d[i-4]+a[i-1]-a[i-4],d[i-6]+a[i-1]-a[i-6]);
        printf("%lld\n",d[n]*2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44691917/article/details/107495389