AcWing 802. 区间和
原题链接
简单
作者:
Stack456
,
2021-04-28 21:30:14
,
所有人可见
,
阅读 184
unique函数使用过程
- 不仅要复制 ,而且要递增
题目注意事项
- 进行增加数字的时候,需要注意下标可能是重合的部分
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef pair<int, int> pII;
vector<int> alls;
vector<pII> add, query;
const int N = 300010;
int n, m;
int a[N], s[N];
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 l;
}
vector<int>::iterator unique( vector<int>::iterator &fi, vector<int>::iterator &se)
{
vector<int>::iterator it = fi;
fi++;
for(; fi != se; fi++)
if((*fi) != *(it))
{
*it = *fi;
it++;
}
return ++it;
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
{
int x, y; scanf("%d%d", &x, &y);
add.push_back({x,y});
alls.push_back(x);
}
while(m --)
{
int l, r;
cin >> l >> r;
alls.push_back(r);
alls.push_back(l);
query.push_back({l,r});
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
for(auto c : add)
{
int x = find(c.first);
x++;
a[x] += c.second; //可能之前是有相同的数值,所以需要+=;
}
for(int i = 1, len = alls.size(); i <= len; i ++)
{
s[i] = s[i - 1] + a[i];
}
for(auto c : query)
{
int l = find(c.first), r = find(c.second);
r++, l++;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}