这竟然是一道贪心题,然而我在不看题解之前一直以为是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<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdlib> 7 #include<cctype> 8 #include<vector> 9 #include<stack> 10 #include<queue> 11 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 pair<int, int> 42 #define mp make_pair 43 #define fir first 44 #define sec second 45 priority_queue<pr, vector<pr>, greater<pr> > q; 46 47 int main() 48 { 49 n = read(); k = read(); 50 for(int i = 1; i <= n; ++i) a[i] = read(); 51 for(int i = 1; i < n; ++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 <= k; ++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 }
原文地址:https://www.cnblogs.com/mrclr/p/9849663.html
时间: 2024-11-02 23:49:43