标签:
由于深感自己水平低下,把大部分有效时间放在了刷题上,于是好久没写题解了。今天刚学了下划分树的原理,于是写道简单题练练手。
题目链接:http://poj.org/problem?id=2104
划分树的空间复杂度和时间复杂度均为O(nlogn),对于解决该问题而言,每次查询的复杂度为O(logn),比归并树O((log)^3)节省时间[归并树采用了三次二分]。
但是划分树也有自己的缺点,不支持更新以及适用范围狭窄,总之...是时代的眼泪了= =
AC代码:
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef long long LL; #define lson ll, mid, deep + 1 #define rson mid + 1, rr, deep + 1 #define MAXN 100010 #define MAX_DEEP 25 int tree[MAX_DEEP][MAXN]; int ToLeft[MAX_DEEP][MAXN]; int input[MAXN]; int n, m; void build(int ll, int rr, int deep) { if(ll == rr) return ; int mid = (ll + rr) >> 1; int same_num = mid - ll + 1; //记录答案相同的个数 for(int i = ll; i <= rr; i++) { if(tree[deep][i] < input[mid]) same_num--; } int l_st = ll, r_st = mid + 1; for(int i = ll; i <= rr; i++) { int flag = 0; if((tree[deep][i] < input[mid]) || (tree[deep][i] == input[mid] && same_num > 0)) { flag = 1; tree[deep+1][l_st++] = tree[deep][i]; if(tree[deep][i] == input[mid]) same_num--; } else { tree[deep+1][r_st++] = tree[deep][i]; } ToLeft[deep][i] = ToLeft[deep][i - 1] + flag; } build(lson); build(rson); } int query(int ll, int rr, int k, int L, int R, int deep) { if(ll == rr) return tree[deep][ll]; int mid = (L + R) >> 1; int lx = ToLeft[deep][ll - 1] - ToLeft[deep][L - 1];//ll左边放于左子树的个数 int ly = ToLeft[deep][rr] - ToLeft[deep][L - 1];//到rr为止放于左子树的个数 int cnt = ly - lx; //区间[ll, rr]放于左子树的个数 int ry = rr - L - ly; //到rr右边为止放于右子树的个数 int rx = ll - L - lx; //ll左边放于右子树的个数 if(cnt >= k) return query(L + lx, L + ly - 1, k, L, mid, deep + 1); else return query(mid + rx + 1, mid + ry + 1, k - cnt, mid + 1, R, deep + 1); } int main() { while(~scanf("%d%d", &n, &m)) { for(int i = 1; i <= n; i++) { scanf("%d", &input[i]); tree[0][i] = input[i]; } sort(input + 1, input + 1 + n); build(1, n, 0); for(int i = 1; i <= m; i++) { int st, ed, k; scanf("%d%d%d", &st, &ed, &k); printf("%d\n", query(st, ed, k, 1, n, 0)); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/gaoxiang36999/p/4570096.html