Discretization part

Discretization

①: Order to be guaranteed

Sort, judge heavy, dichotomy

vector<int>alls;

int find(int x){
    
     //二分
    int l = 0, r = alls.size();
    while(l < r){
    
    
        int mid = l+ r >> 1;
        if(alls[mid] >= x)r = mid;
        else l = mid + 1;
    }
    return r + 1;
}

sort(alls.begin(),alls.end()); //排序
alls.erase(unique(alls.begin(),alls.end()),alls.end()); //判重

②: Order not required

map or hash table

int n;
map<int,int>s;
int get(int x) {
    
    
	if (s.count(x) == 0)s[x] = ++n;
	return s[x];
}

AcWing 802. Interval and

Suppose there is an infinite number line, and each coordinate on the number line is 0.

Now, we first perform n operations, and each operation adds c to the number at a certain position x.

Next, make m queries. Each query contains two integers l and r. You need to find the sum of all the numbers in the interval [l, r].

Input format

The first line contains two integers n and m.

Next n lines, each line contains two integers x and c.

Next, m lines, each line contains two integers l and r.

Output format

There are m lines in total, and each line outputs the sum of the numbers in the interval sought in the query.

data range

− 1 0 9 ≤ x ≤ 1 0 9 −10^{9}≤x≤10^{9} 109x109
1 ≤ n , m ≤ 1 0 5 1≤n,m≤10^{5} 1n,m105
− 1 0 9 ≤ l ≤ r ≤ 1 0 9 −10^{9}≤l≤r≤10^{9} 109lr109
− 10000 ≤ c ≤ 10000 −10000≤c≤10000 10000c10000

Code

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
const int N = 300010;
int a[N], s[N];

vector<int>alls;
vector<PII>add, query;
int find(int x){
    
    
    int l = 0, r = alls.size();
    while(l < r){
    
    
        int mid = l+ r >> 1;
        if(alls[mid] >= x)r = mid;
        else l = mid + 1;
    }
    return r + 1;
}

int main(){
    
    
    int n,m;cin >> n >>m;
    for(int i=1;i<=n;++i){
    
    
        int x,c;cin >> x >>c;
        alls.push_back(x);
        
        add.push_back({
    
    x,c});
    }
    for(int i=1;i<=m;++i){
    
    
        int l,r;cin >> l >>r;
        query.push_back({
    
    l,r});
        alls.push_back(l);
        alls.push_back(r);
    }
    sort(alls.begin(),alls.end());
    alls.erase(unique(alls.begin(),alls.end()),alls.end());
    
    for(auto it:add){
    
    
        int x = find(it.first);
        a[x] += it.second;
    }
    
    for(int i = 1;i<=alls.size();++i){
    
    
        s[i] = s[i - 1] + a[i];
    }
    
    for(auto it :query){
    
    
        int l = find(it.first);
        int r = find(it.second);
        printf("%d\n",s[r] - s[l - 1]);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/zzq0523/article/details/109251671