标签:
Description
Input
Output
Sample Input
7 3 1 5 2 6 3 7 4 2 5 3 4 4 1 1 7 3
Sample Output
5 6 3
题目大意:
求区间第k小。
分析:
可持久化线段树,按序列中的数的顺序来创建新版本,每个数在线段树中所在的位置为数在所有数中第几小。
代码:
1 #include <cstdio> 2 #include <algorithm> 3 4 const int Max_N = 2000000; 5 6 struct SegmentTree 7 { 8 int Child[2]; 9 int Count, Number; 10 } tree[Max_N]; 11 12 int Root[Max_N], treeSize; 13 int num[Max_N], id[Max_N], back[Max_N]; 14 int n, m, qi, qj, qk; 15 16 #define MID ((left + right) >> 1) 17 18 int Build (int left, int right) 19 { 20 int i = ++treeSize; 21 tree[i].Count = 0; 22 if (left < right) 23 { 24 tree[i].Child[0] = Build (left, MID); 25 tree[i].Child[1] = Build (MID + 1, right); 26 } 27 return i; 28 } 29 30 int Modify (int left, int right, int pos, int key, int pre) 31 { 32 int i = ++treeSize; 33 if (left < right) 34 { 35 int ch = (pos <= MID) ? 0 : 1; 36 tree[i].Child[!ch] = tree[pre].Child[!ch]; 37 ch ? left = MID + 1 : right = MID; 38 tree[i].Child[ch] = Modify (left, right, pos, key, tree[pre].Child[ch]); 39 tree[i].Count = tree[tree[i].Child[0]].Count + tree[tree[i].Child[1]].Count; 40 }else tree[i].Number = key, tree[i].Count = 1; 41 return i; 42 } 43 44 #define LEFTSIZE (tree[tree[late].Child[0]].Count - tree[tree[early].Child[0]].Count) 45 46 int Query (int left, int right, int early, int late, int k) 47 { 48 if (left == right) return tree[late].Number; 49 int ch = (k <= LEFTSIZE) ? 0 : 1; 50 ch ? left = MID + 1 : right = MID; 51 return Query (left, right, tree[early].Child[ch], tree[late].Child[ch], ch ? k - LEFTSIZE : k); 52 } 53 54 bool cmp (int a, int b) 55 { 56 return num[a] < num[b]; 57 } 58 59 int main () 60 { 61 scanf ("%d %d", &n, &m); 62 for (int i = 1; i <= n; i++) 63 scanf ("%d", &num[i]), id[i] = i; 64 std::sort (id + 1, id + n + 1, cmp); 65 Root[0] = Build (1, n); 66 for (int i = 1; i <= n; i++) 67 back[id[i]] = i; 68 for (int i = 1; i <= n; i++) 69 Root[i] = Modify (1, n, back[i], num[i], Root[i - 1]); 70 for (int i = 0; i < m; i++) 71 { 72 scanf ("%d %d %d", &qi, &qj, &qk); 73 printf ("%d\n", Query (1, n, Root[qi - 1], Root[qj], qk)); 74 } 75 }
标签:
原文地址:http://www.cnblogs.com/lightning34/p/4388229.html