今天学的整数有序离散,感觉比前边讲的都难些,那就来讲讲这道题,其实这道题,给我的第一感觉使用线段树或者树状数组来做都是可以的,但是今天学的离散那就用离散来写.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int, int>PII;
int n, m;
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() - 1;
while (l < r)
{
int mid = l + r >> 1;
if (alls[mid] >= x) r = mid;
else l = mid + 1;
}
return r + 1; //为什么是r+1.因为离散之后从1开始,不是零
}
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.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)//遍历add中的每一个元素并将值赋给item
{
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;
}
}
在代码里面有一些基本的注释,下面我来讲解一下这道题这个方法大致的思路:
首先,程序会读取输入的n和m值。然后,对于n次循环,程序会读取输入的x和c值,并将其存入add向量中。同时,x值也会被存入alls向量中。接着,对于m次循环,程序会读取输入的l和r值,并将其存入query向量中。同时,l和r值也会被存入alls向量中。接下来,程序会对alls向量进行排序,并去除重复元素。然后,程序会根据find函数找到x在alls中的位置,并将对应的a[x]值增加item.second。接着,程序会预处理前缀和s[i] = s[i - 1] + a[i]。最后,程序会根据查询的范围找到对应位置的前缀和,并输出结果。
下面来讲解一下代码中的alls.erase(unique(alls.begin(), alls.end()), alls.end()); 这是一个去重的操作,就是你首先把整个alls的说有数据传入unique中去,这个函数是去重的,返回的是去完重之后的最后一个元素的位置,然后erase再删除现在去完重之后的最后一个元素的位置到原本alls里最后一个元素的最后一个值,便实现好了去重.