[APIO/CTSC 2007]数据备份

2021-07-04 19:06

阅读:476

标签:小根堆   getch   nbsp   char   tchar   循环   span   ref   view   

嘟嘟嘟

 

这竟然是一道贪心题,然而我在不看题解之前一直以为是dp。

首先最优的配对一定是相邻两个建筑物配对,所以我们求出差分数组,就变成了在n - 1个数中选出不相邻的k个数,使这k个数的和最小。

贪心是在回事呢?首先把所有点放在一个小根堆中,然后如果取出一个点ai,就把ai-1 + ai+1 - ai放到小根堆中,这样如果以后选了ai-1 + ai+1 - ai这个数,就把前面选的ai抵消了,所以这两次操作就相当于选了ai-1和ai+1这两个数。

每选一次就合并了两个数,那么进行k次就选了k个数,所以循环k次后,累加的答案就是最优解。

技术分享图片技术分享图片
 1 #include 2 #include 3 #include 4 #include
 5 #include 6 #include 7 #include 8 #include 9 #include10 #include11 using namespace std;
12 #define enter puts("") 
13 #define space putchar(‘ ‘)
14 #define Mem(a, x) memset(a, x, sizeof(a))
15 #define rg register
16 typedef long long ll;
17 typedef double db;
18 const int INF = 1e9;
19 const db eps = 1e-8;
20 const int maxn = 1e5 + 5;
21 inline ll read()
22 {
23   ll ans = 0;
24   char ch = getchar(), last =  ;
25   while(!isdigit(ch)) {last = ch; ch = getchar();}
26   while(isdigit(ch)) {ans = ans * 10 + ch - 0; ch = getchar();}
27   if(last == -) ans = -ans;
28   return ans;
29 }
30 inline void write(ll x)
31 {
32   if(x 0) x = -x, putchar(-);
33   if(x >= 10) write(x / 10);
34   putchar(x % 10 + 0);
35 }
36 
37 int n, k, a[maxn];
38 int dif[maxn], pre[maxn], nxt[maxn];
39 ll ans = 0;
40 
41 #define pr pair42 #define mp make_pair
43 #define fir first
44 #define sec second
45 priority_queue, greater > q;
46 
47 int main()
48 {
49   n = read(); k = read();
50   for(int i = 1; i  read();
51   for(int i = 1; i i)
52     {
53       dif[i] = a[i + 1] - a[i];
54       pre[i] = i - 1; nxt[i] = i + 1;
55       q.push(mp(dif[i], i));
56     }
57   nxt[n - 1] = 0;
58   for(int i = 1; i i)
59     {
60       pr now = q.top(); q.pop();
61       if(now.fir != dif[now.sec]) {k++; continue;}  //合并后就跳过
62       ans += now.fir;
63       int ls = pre[now.sec], rs = nxt[now.sec];
64       nxt[now.sec] = nxt[rs]; pre[nxt[now.sec]] = now.sec;
65       pre[now.sec] = pre[ls]; nxt[pre[now.sec]] = now.sec;
66       dif[now.sec] = (ls && rs) ? dif[ls] + dif[rs] - dif[now.sec] : INF;
67       dif[ls] = dif[rs] = INF;
68       q.push(mp(dif[now.sec], now.sec));
69     }
70   write(ans), enter;
71   return 0;
72 }
View Code

 

[APIO/CTSC 2007]数据备份

标签:小根堆   getch   nbsp   char   tchar   循环   span   ref   view   

原文地址:https://www.cnblogs.com/mrclr/p/9849663.html


评论


亲,登录后才可以留言!