本文主要是介绍【LOJP4137】Rmq Problem / mex 主席树求区间MEX,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送⻔
题意
分析
我们用主席树维护每一个数最后一次出现的位置,然后每次查询就在第 r r r棵树上求最小的,位置小于 l l l的数
代码
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
VI nums;
int n,m,idx,a[N];
int root[N];
struct Node{int l,r;int mi;
}tr[N * 50];int find(int x){return lower_bound(nums.begin(),nums.end(),x) - nums.begin();
}int build(int l,int r){int p = ++idx;if(l == r) return p;int mid = (l + r) >> 1;tr[p].l = build(l,mid),tr[p].r= build(mid + 1,r);return p;
}int insert(int p,int l,int r,int x,int val){int q = ++idx;tr[q] = tr[p];if(l == r){tr[q].mi = val;return q;}int mid = (l + r) >> 1;if(x <= mid) tr[q].l = insert(tr[q].l,l,mid,x,val);else tr[q].r = insert(tr[q].r,mid + 1,r,x,val);tr[q].mi = min(tr[tr[q].l].mi,tr[tr[q].r].mi);return q;
}int query(int p,int l,int r,int x){if(l == r) return l;int mid = (l + r) >> 1;if(tr[tr[p].l].mi < x) return query(tr[p].l,l,mid,x);return query(tr[p].r,mid + 1,r,x);
}int main() {read(n),read(m);nums.pb(0);for(int i = 1;i <= n;i++){read(a[i]);nums.pb(a[i]),nums.pb(a[i] + 1);}sort(nums.begin(),nums.end());nums.erase(unique(nums.begin(),nums.end()),nums.end());root[0] = build(0,nums.size() - 1);for(int i = 1;i <= n;i++) root[i] = insert(root[i - 1],0,nums.size() - 1,find(a[i]),i);while(m--){int l,r;read(l),read(r);int x = query(root[r],0,nums.size() - 1,l);di(nums[x]);}return 0;
}
这篇关于【LOJP4137】Rmq Problem / mex 主席树求区间MEX的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!