传送门
题意
分析
跟牛客第一场的那个最小匹配的题有点像,但又不太一样
首先两个数字匹配的话,最小的代价肯定是在有序情况下和相邻的数进行组合,但这道题涉及到一个决策问题,是算代价还是丢到卡车里面
我们分别处理两个决策,状态转移方程就比较明显了
if(j) f[i][j] = min(f[i - 1][j - 1],f[i][j]);
f[i][j] = min(f[i - 2][j] + a[i] - a[i - 1],f[i][j]);
}
f [ i ] [ j ] f[i][j] f[i][j]表示前 i i i个物品有 j j j个在卡车上
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
ll a[N];
ll f[N][30];
int n,m;
int main() {
read(n),read(m);
for(int i = 1;i <= 2 * n + m;i++) read(a[i]);
sort(a + 1,a + 1 + 2 * n + m);
memset(f,0x3f,sizeof f);
for(int i = 0;i <= m;i++) f[i][i] = 0;
for(int i = 1;i <= 2 * n + m;i++)
for(int j = 0;j <= m;j++){
if(j) f[i][j] = min(f[i - 1][j - 1],f[i][j]);
if(i >= 2)f[i][j] = min(f[i - 2][j] + a[i] - a[i - 1],f[i][j]);
}
dl(f[2 * n + m][m]);
return 0;
}