Fork me on GitHub

P3028 汽水机(差分)

题目

P3028 [USACO10OCT]汽水机Soda Machine

解析

差分,看到\(a[i]\leq 1e9\),离散化一下,在\(l\)\(+1\)\(r+1\)\(-1\),这样就只有\(2n\)个点了,再按位置排一下序,扫一遍记录答案就可以了。
需要注意的是,如果在某个位置既有\(+1\)操作又有\(-1\)操作,要先\(-1\)\(+1\),否则在统计答案的时候会多算
强化版

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;

int sum, ans, n;

struct node {
    int pos, val;
    bool operator<(const node & oth) const {
        return pos == oth.pos ? val < oth.val : pos < oth.pos;
    }
} e[N];

int main() {
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 1, x, y; i <= n; ++i) {
        cin >> x >> y;
        e[i] = (node) {x, 1}, e[i + n] = (node) {y + 1, -1};
    }
    sort(e + 1, e + 1 + n + n);
    for (int i = 1; i <= n + n; ++i) {
        sum += e[i].val;
        ans = max(ans, sum);
    }
    cout << ans;
}


posted @ 2019-10-28 19:26  Chrety  阅读(279)  评论(0编辑  收藏  举报