L3-017 森森快递(线段树 + 贪心)

题目链接

思路:
区间活动选择贪心 + 线段树区改、维护区间最小值。
区间贪心:区间的 r 值越小越先修改,当区间 r 值相同 l 越小越先修改,用一个结构体储存排序即可。
注意:区间修改时父节点的修改不是长度*k值,是直接+=k,因为区间维护的是最小值,
INF要大于int类型,INF=0x3f3f3f3f有一个点wa了,改成INF = 1e15就过了。

代码:

#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
#define lson idx << 1
#define rson idx << 1 | 1

using namespace std;

typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 2e5 + 10;
const ll INF = 1e15;
const double eps = 1e-6;
const int mod = 998244353;

int n, m;
struct node
{
    int l, r;
    ll w;
} tree[N << 2];
ll lazy[N << 2];
int a[N];
struct node2
{
    int l, r;
} b[N];

bool cmp(node2 x, node2 y)
{
    if (x.r < y.r)
        return true;
    else if (x.r == y.r && x.l < y.l)
        return true;
    return false;
}

inline void PushUp(int idx)
{
    tree[idx].w = min(tree[lson].w, tree[rson].w);
}

inline void PushDown(int idx)
{
    if (lazy[idx] != 0)
    {
        lazy[lson] += lazy[idx];
        lazy[rson] += lazy[idx];
        tree[lson].w += lazy[idx];
        tree[rson].w += lazy[idx];
        lazy[idx] = 0;
    }
}

void Build(int idx, int l, int r)
{
    lazy[idx] = 0;
    tree[idx].l = l;
    tree[idx].r = r;
    if (l == r)
    {
        tree[idx].w = a[l];
        return;
    }
    int mid = l + r >> 1;
    Build(lson, l, mid);
    Build(rson, mid + 1, r);
    PushUp(idx);
}

inline void Update(int idx, int l, int r, ll k)
{
    if (tree[idx].l >= l && tree[idx].r <= r)
    {
        tree[idx].w += k;
        lazy[idx] += k;
        return;
    }
    PushDown(idx);
    if (tree[lson].r >= l)
        Update(lson, l, r, k);
    if (tree[rson].l <= r)
        Update(rson, l, r, k);
    PushUp(idx);
}

inline ll Query(int idx, int l, int r)
{
    if (tree[idx].l >= l && tree[idx].r <= r)
        return tree[idx].w;
    PushDown(idx);
    ll ans = INF;
    if (tree[lson].r >= l)
        ans = min(Query(lson, l, r), ans);
    if (tree[rson].l <= r)
        ans = min(Query(rson, l, r), ans);
    return ans;
}

int main()
{
    fastio;
    cin >> n >> m;
    n--;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    Build(1, 1, n);
    for (int i = 1; i <= m; i++)
    {
        cin >> b[i].l >> b[i].r;
        if (b[i].l > b[i].r)
            swap(b[i].l, b[i].r);
        b[i].l++;
    }
    sort(b + 1, b + m + 1, cmp);
    ll ans = 0;
    for (int i = 1; i <= m; i++)
    {
        ll k = Query(1, b[i].l, b[i].r);
        ans += k;
        Update(1, b[i].l, b[i].r, -k);
    }
    cout << ans << endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值