天天看點

802. 區間和

假定有一個無限長的數軸,數軸上每個坐标上的數都是 0。

現在,我們首先進行 n 次操作,每次操作将某一位置 x 上的數加 c。

接下來,進行 m 次詢問,每個詢問包含兩個整數 l 和 r,你需要求出在區間 [l,r] 之間的所有數的和。

輸入格式

第一行包含兩個整數 n 和 m。

接下來 n 行,每行包含兩個整數 x 和 c。

再接下來 m 行,每行包含兩個整數 l 和 r。

輸入樣例:
3 3
1 2
3 6
7 5
1 3
4 6
7 8
輸出樣例:
8
0
5      
#include<iostream>
#include<vector>
#include<algorithm>
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;//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 r+1;
}

int main(){
    cin>>n>>m;
    
    for(int i =0; i < n; i++){
        int x ,c ;//在下标為x的位置加c
        cin>>x>>c;
        add.push_back({x,c});
        
        //要将下标x離散化 ,需要将其存入alls數組中
        alls.push_back(x);
    }
     
    for(int i=0;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 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),r = find(item.second);
        cout<<s[r]-s[l-1]<<endl;
    }
    
    return 0;
        
}      

繼續閱讀