# 洛谷 [P3620] 数据备份

## 贪心神题

f[i][j]表示考虑前i个点，已经形成j对点的最小距离，num[i]表示第i个点的坐标。

f[i][j]=min(f[i-1][j],f[i-2][j-1]+num[i]-num[i-1]);

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#define ll long long
using namespace std;
const int MAXN = 100005;
int init() {
int rv = 0, fh = 1;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') fh = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
rv = (rv<<1) + (rv<<3) + c - '0';
c = getchar();
}
return fh * rv;
}
int n, k, loc[MAXN], num[MAXN], pre[MAXN], nxt[MAXN];
struct node {
int wei, id;
bool operator < (const node & b) const{
return b.wei < wei;
}
};
priority_queue<node> hea;
bool del[MAXN];
ll ans;
int main() {
n = init(); k = init();
for(int i = 1; i <= n; i++) {
loc[i] = init();
if(i >= 2) {
num[i - 1] = loc[i] - loc[i - 1];
hea.push((node){num[i - 1], i - 1});
}
}
for(int i = 1; i <= n; i++) {
pre[i] = i - 1; nxt[i] = i + 1;
}
nxt[0] = 1; nxt[n] = 0;
num[0] = num[n] = 0x3f3f3f3f;
for(int i = 1; i <= k; i++) {
while(del[hea.top().id]) hea.pop();
ans += hea.top().wei;int x = hea.top().id; hea.pop();
int l = pre[x], r = nxt[x];
del[l] = del[r] = 1;
hea.push((node){num[x] = num[l] + num[r] - num[x], x});
pre[x] = pre[l]; nxt[x] = nxt[r];
pre[nxt[r]] = x; nxt[pre[l]] = x;
}
cout << ans << endl;
return 0;
}

posted @ 2018-05-03 20:09  Mr_Wolfram  阅读(79)  评论(1编辑  收藏