[USACO13DEC]Optimal Milking G【线段树维护最大独立集】

题目链接 P3097 [USACO13DEC]Optimal Milking G


  很明显的是这道题有4e4个点,直接跑最大独立集的话,那么测评机承受不起啊!所以,这里要维护一个区间dp的形式。

  每个区间有左右两个端点,我们现在要合并两个区间的话,会有一些情况:

  1. 【0,0】:左右端点都不选;
  2. 【0,1】:左端点不选,右端点选;
  3. 【1,0】:左端点选,右端点不选;
  4. 【1,1】:左端点选,右端点也选。

  然后,直接用线段树维护一个区间dp即可。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <unordered_map>
#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define eps 1e-8
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
#define MAX_3(a, b, c) max(a, max(b, c))
#define MAX_4(a, b, c, d) max(max(a, b), max(c, d))
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 4e4 + 7;
int N, M;
ll a[maxN], tree[maxN << 2][4]; //0:[0,0], 1:[0,1], 2:[1,0], 3[1,1]
inline void pushup(int rt)
{
    tree[rt][0] = MAX_3(tree[lsn][1] + tree[rsn][0], tree[lsn][0] + tree[rsn][2], tree[lsn][0] + tree[rsn][0]);
    tree[rt][1] = max(tree[lsn][0] + tree[rsn][3], tree[lsn][1] + tree[rsn][1]);
    tree[rt][2] = max(tree[lsn][3] + tree[rsn][0], tree[lsn][2] + tree[rsn][2]);
    tree[rt][3] = max(tree[lsn][2] + tree[rsn][3], tree[lsn][3] + tree[rsn][1]);
}
void buildTree(int rt, int l, int r)
{
    if(l == r)
    {
        tree[rt][0] = tree[rt][1] = tree[rt][2] = 0;
        tree[rt][3] = a[l];
        return;
    }
    int mid = HalF;
    buildTree(Lson); buildTree(Rson);
    pushup(rt);
}
void update(int rt, int l, int r, int qx, ll val)
{
    if(l == r) { tree[rt][3] = val; return; }
    int mid = HalF;
    if(qx <= mid) update(Lson, qx, val);
    else update(Rson, qx, val);
    pushup(rt);
}
int main()
{
    scanf("%d%d", &N, &M);
    for(int i=1; i<=N; i++) scanf("%lld", &a[i]);
    buildTree(1, 1, N);
    ll ans = 0;
    for(int i=1, x, y; i<=M; i++)
    {
        scanf("%d%d", &x, &y);
        update(1, 1, N, x, y);
        ans += MAX_4(tree[1][0], tree[1][1], tree[1][2], tree[1][3]);
    }
    printf("%lld\n", ans);
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值