标签:class unique 推荐 div target 时空 大小 lan find
离散化,把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。
通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。
模板题链接:区间和
代码如下:
#include <iostream> #include <algorithm> #include <vector> using namespace std; const int N = 100010; vector<int> alls; int n, m; int x[N], c[N], l[N], r[N]; int a[N * 3], s[N * 3]; // 找到x在alls中的下标 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() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i ++ ) { scanf("%d%d", &x[i], &c[i]); alls.push_back(x[i]); } for (int i = 0; i < m; i ++ ) { scanf("%d%d", &l[i], &r[i]); alls.push_back(l[i]), alls.push_back(r[i]); } // 排序 + 判重 sort(alls.begin(), alls.end()); alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 插入操作 for (int i = 0; i < n; i ++ ) a[find(x[i])] += c[i]; // 预处理前缀和 for (int i = 1; i <= alls.size(); i ++ ) s[i] = s[i - 1] + a[i]; // 查询操作 for (int i = 0; i < m; i ++ ) printf("%d\n", s[find(r[i])] - s[find(l[i]) - 1]); return 0; }
推荐习题:赶牛入圈(POJ3179)
标签:class unique 推荐 div target 时空 大小 lan find
原文地址:https://www.cnblogs.com/ninedream/p/11241165.html