(离散化) acwing 802. 区间和
作者:互联网
802. 区间和
题目链接https://www.acwing.com/problem/content/804/
题目:
思路:把出现的点都保存起来,最多3*n个,然后排序去重。在二分查找点,然后进行加运算和查询运算,0(mlogn).查询之前要先求出前缀和
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<utility>
#include<vector>
using namespace std;
typedef pair<int ,int >PII;
vector<PII > a,q;
vector<int >b;
int sum[300010];
int findd(int u){
int l=0,r=b.size()-1;
while(l<r){
int mid=l+r+1>>1;
if(u>=b[mid]) l=mid;
else r=mid-1;
}
return l+1;
}
int main(){
int n,m;
cin>>n>>m;
int x,y;
for(int i=0;i<n;i++){
scanf("%d%d",&x,&y);
a.push_back({x,y});
b.push_back(x);
}
for(int i=0;i<m;i++){
scanf("%d%d",&x,&y);
q.push_back({x,y});
b.push_back(x);
b.push_back(y);
}
sort(b.begin(),b.end());
b.erase(unique(b.begin(),b.end()),b.end());
for(int i=0;i<n;i++){
int t=findd(a[i].first);
sum[t]+=a[i].second;
}
for(int i=0;i<b.size();i++){
sum[i+1]+=sum[i];
}
for(int i=0;i<m;i++){
int l=findd(q[i].first);
int r=findd(q[i].second);
printf("%d\n",sum[r]-sum[l-1]);
}
return 0;
}
标签:int,sum,back,mid,离散,push,802,include,acwing 来源: https://blog.csdn.net/weixin_46028214/article/details/116901990