POJ - 2104 [K-th Number] Chairman of the tree bare title
https://cn.vjudge.net/contest/304073#problem
The meaning of problems
Given n and m times the number of inquiries, each query [l, r] small numbers of K within the interval is.
analysis
This is the President of trees. Chairman of the tree, the name comes from the inventor HJT(%%%). Chairman of the tree considered variants segment tree, known as persistent segment tree can be saved and updated version of the query history, each will generate a new weight segment tree (refer to save the segment tree leaf node is the current value number) .
Of course, we can not re-established every time a new tree can be found by looking at every single point update, the leaf node node on which a chain is only from the root to the current changes carried out. With this property, for each update, we just need to create a new root node, then recursively need to create a new (updated) node.
Code
Bare board question or write a little clearer idea of good.
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 1e5 + 5;
int n, m, cnt, x, y, k;
int root[N], a[N]; // root保存的是历史版本根节点
vector<int> v; // 保存去重后的数组
struct node {
int l, r, sum;
} T[N * 40]; // 线段树*4、主席树*40
int getid(int x) { // 获取每次更新的节点的“位置”
return lower_bound(v.begin(), v.end(), x) - v.begin() + 1;
}
void update(int l, int r, int &x, int y, int pos) {
T[++cnt] = T[y]; // 继承上一棵树
T[cnt].sum ++; // 权值
x = cnt;
if (l == r)
return;
int mid = (l + r) / 2;
if (mid >= pos)
update(l, mid, T[x].l, T[y].l, pos);
else
update(mid + 1, r, T[x].r, T[y].r, pos);
}
int query(int l, int r, int x, int y, int k) {
if (l == r)
return l;
int mid = (l + r) / 2;
int sum = T[T[y].l].sum - T[T[x].l].sum; // 根据所求进行修改
if (sum >= k)
return query(l, mid, T[x].l, T[y].l, k);
else
return query(mid + 1, r, T[x].r, T[y].r, k - sum);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
v.push_back(a[i]);
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end()); // 去重
for (int i = 1; i <= n; i++) {
update(1, n, root[i], root[i - 1], getid(a[i]));
}
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &k);
printf("%d\n", v[query(1, n, root[x - 1], root[y], k) - 1]);
}
return 0;
}