当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 洛谷P1792 [国家集训队]种树(链表 贪心)

洛谷P1792 [国家集训队]种树(链表 贪心)

2019年03月08日  | 移动技术网IT编程  | 我要评论

心路gps主题曲,月光玉,栆

题意

题目链接

sol

最直观的做法是wqs二分+dp。然而还有一种神仙贪心做法。

不难想到我们可以按权值从大到小依次贪心,把左右两边的打上标记,但这显然是错的比如\(1\ 231\ 233\ 232\)。我们会得到\(234\)而不是\(463\)。考虑加入一种反悔机制,也就是说我们可以增加一种决策来取消该决策的影响并加入新的决策的贡献。

考虑这样一种做法:把原来的点权改为\(231 + 232 - 233\),并用双向链表维护前驱后继。把\(233\)的前驱改为\(231\)的前驱并把\(233\)的后继改为\(232\)的后继。这样我们再次选择这个点的贡献的时候就相当于选了\(231 +232\)

复杂度\(o(nlogn)\)

// luogu-judger-enable-o2
#include<bits/stdc++.h> 
#define pair pair<int, int>
#define mp(x, y) make_pair(x, y)
#define fi first
#define se second
#define ll long long 
#define ull unsigned long long 
#define fin(x) {freopen(#x".in","r",stdin);}
#define fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7, inf = 1e9 + 10;
const double eps = 1e-9;
template <typename a, typename b> inline bool chmin(a &a, b b){if(a > b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline bool chmax(a &a, b b){if(a < b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline ll add(a x, b y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename a, typename b> inline void add2(a &x, b y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename a, typename b> inline ll mul(a x, b y) {return 1ll * x * y % mod;}
template <typename a, typename b> inline void mul2(a &x, b y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename a> inline void debug(a a){cout << a << '\n';}
template <typename a> inline ll sqr(a x){return 1ll * x * x;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int n, m, a[maxn], pre[maxn], nxt[maxn], vis[maxn], cnt;
priority_queue<pair> q;
signed main() {
    n = read(); m = read();
    if(m > n / 2) {puts("error!"); return 0;}
    for(int i = 1; i <= n; i++) a[i] = read(), pre[i] = i - 1, nxt[i] = i + 1, q.push({a[i], i});
    pre[1] = n; nxt[n] = 1;
    int ans = 0;
    while(m--) {
        pair p = q.top(); q.pop(); int c = p.se;
        if( vis[c]) {m++; continue;}    
        ans += p.fi;
        a[c] = a[pre[c]] + a[nxt[c]] - a[c]; vis[pre[c]] = 1; vis[nxt[c]] = 1;
        pre[c] = pre[pre[c]]; nxt[c] = nxt[nxt[c]];
        nxt[pre[c]] = c; pre[nxt[c]] = c;
        q.push({a[c], c});
    }
    cout << ans;
    return 0;
}
/*
2
1 1
*/

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网