标签:
区间覆盖问题,区间绝对位置并不重要,重要的是各个更新的区间段之间的相对位置关系。
举例而言,离散化将区间更新[1,100], [2, 50]更换为区间更新[1,4], [2,3]。
离散化可以将空间复杂度从O(L)降到O(N),进而也降低了更新和查询操作的复杂度。
用一个map来记录绝对位置与相对位置间的映射。
需要注意的是,离散化的线段树的叶子节点是[i, i+1]而不是[i, i],区间分解时要考虑到这一点。
代码如下:
#include <stdio.h> #include <cassert> #include <algorithm> #include <cstring> #include <map> #define N 100005 typedef struct _seg_tree_ { int left, right; int val; bool lazy_tag; _seg_tree_ *lson = NULL, *rson = NULL; _seg_tree_(int left_idx, int right_idx, int value) : left(left_idx), right(right_idx), val(value), lazy_tag(false) {} } seg_tree, *pseg_tree; int data[2 * N]; int sorted_data[2 * N]; std::map<int, int> seq_map; bool visible[N]; pseg_tree construct_seg_tree(int left, int right) { if (left + 1 == right) { return new seg_tree(left, right, 0); } int mid = left + (right - left) / 2; pseg_tree lson = construct_seg_tree(left, mid); pseg_tree rson = construct_seg_tree(mid, right); pseg_tree ans = new seg_tree(left, right, 0); ans->lson = lson; ans->rson = rson; return ans; } void lazy_down(pseg_tree proot) { proot->lazy_tag = false; if (proot->lson != NULL) { proot->lson->lazy_tag = true; proot->lson->val = proot->val; } if (proot->rson != NULL) { proot->rson->lazy_tag = true; proot->rson->val = proot->val; } } void query_seg_tree(pseg_tree proot) { if (proot->lazy_tag == true) { visible[proot->val] = true; return; } if (proot->lson != NULL) { query_seg_tree(proot->lson); } if (proot->rson != NULL) { query_seg_tree(proot->rson); } } void modify_seg_tree(pseg_tree proot, int left, int right, int val) { if (left == proot->left && right == proot->right) { proot->val = val; proot->lazy_tag = true; return; } int mid = proot->left + (proot->right - proot->left) / 2; if (proot->lazy_tag == true) { lazy_down(proot); } if (left >= mid) { modify_seg_tree(proot->rson, left, right, val); } else if (right <= mid) { modify_seg_tree(proot->lson, left, right, val); } else { modify_seg_tree(proot->rson, mid, right, val); modify_seg_tree(proot->lson, left, mid, val); } } int main(){ int n, l; scanf("%d%d", &n, &l); for (int i = 0; i < n; i++) { scanf("%d%d", data + 2 * i, data + 2 * i + 1); } memcpy(sorted_data, data, 2 * n * sizeof(int)); std::sort(sorted_data, sorted_data + 2 * n); int len = std::unique(sorted_data, sorted_data + 2 * n) - sorted_data; for (int i = 0; i < len; i++) { seq_map.insert(std::make_pair(sorted_data[i], i + 1)); } pseg_tree proot = construct_seg_tree(1, len); for (int i = 0; i < n; i++) { int l = seq_map.find(data[2 * i])->second; int r = seq_map.find(data[2 * i + 1])->second; modify_seg_tree(proot, l, r, i + 1); } query_seg_tree(proot); int ans = 0; for (int i = 1; i <= n; i++) { if (visible[i]) ans++; } printf("%d\n", ans); return 0; }
标签:
原文地址:http://www.cnblogs.com/xblade/p/4541694.html