离散化

原题链接

离散化核心思想是将很分散的大数经过pair建立映射,通过二分来查找值。本题是先将所有可能访问到的点存下,再将每个点加多少映射到a数组,最后通过query来二分查找起始点。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

typedef pair<int, int> PII;

const int N = 300010;

int n, m;
int a[N], s[N];

vector<int> alls;
vector<PII> add, query;

int find(int x)
{
    int l = 0, r = alls.size() - 1;
    while (l < r)
    {
        int mid = l + r >> 1;
        if (alls[mid] >= x)
            r = mid;
        else
            l = mid + 1;
    }
    return l + 1;//前缀和下标从1开始,所以要返回l+1
}

vector<int>:: iterator unique(vector<int> &alls)
{
    int j = 0;
    for (int i = 0; i < alls.size(); i ++)
    {
        if (i != 0 && alls[i] != alls[i - 1])
        {
            alls[j++] = alls[i];
        }
    }
    return alls.begin() + j;
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i ++)
    {
        int x, c;
        cin >> x >> c;
        add.push_back({x, c});
        alls.push_back(x);
    }
    for (int i = 0; i < m; i ++)
    {
        int l, r;
        cin >> l >> r;
        query.push_back({l, r});
        //alls里加这个是为了防止l和r找不到
        alls.push_back(l);
        alls.push_back(r);
    }

    sort(alls.begin(), alls.end());
    alls.erase(unique(alls), alls.end());

    for (auto item: add)
    {
        int x = find(item.first);
        a[x] += item.second;
    }

    for (int i = 1; i <= alls.size(); i ++)
    {
        s[i] = s[i - 1] + a[i];
    }

    for (auto item : query)
    {
        int l = find(item.first);
        int r = find(item.second);
        cout << s[r] - s[l - 1] << endl;
    }
}

区间合并

原题链接

本题也可以用贪心求解。区间合并思路是排序后先确定起始的左端点,然后逐个往后找,如果找到一个区间左端点在当前区间右端点的右边,就把当前区间存下来,把下一个区间再当作起始区间。这有一个细节是在merge函数最后要再加个判断,防止最后一组区间没有被存下。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

typedef pair<int, int> PII;

vector<PII> segs;

void merge(vector<PII> &segs)
{
    vector<PII> t;
    int l = -2e9, r = -2e9;
    sort(segs.begin(), segs.end());
    for (auto item: segs)
    {
        //合并
        if (r >= item.first)
        {
            r = max(r, item.second);
        }
        //新区间
        else
        {
            if (l == -2e9)
            {
                l = item.first;
                r = item.second;
            }
            else
            {
                t.push_back({l, r});
                l = item.first;
                r = item.second;
            }
        }
    }
    if(l != -2e9) t.push_back({l,r});
    segs = t;
}

int main()
{
    int n;
    cin >> n;
    while (n --)
    {
        int l, r;
        cin >> l >> r;
        segs.push_back({l, r});
    }
    merge(segs);
    cout << segs.size();
}
最后修改:2022 年 03 月 30 日
如果觉得我的文章对你有用,请随意赞赏