您的位置:首页 > 其它

hust 1628 LowerBound 莫队算法

2016-02-08 15:47 465 查看

题目

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105318#problem/C

题目来源:2016寒假第二次高年级训练

简要题意:找到下标[L,R][L,R]内大于VV的最小的数。

题解

没学过莫队的可参考这份题解的E去学习莫队

弄个map来维护区间内的数,然后用莫队来加速过程就行了。

需要注意区间移动的顺序,为防止个数变负数,应该先增后减。

本题也可以使用数据结构(如主席树)来搞,不过莫队简洁易懂,效率也不低。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
const int blk = 300;
const int N = 1e5+5;
const int NEXIST = 2e9+15;

struct Node {
int l, r, v, id;
};

int pos
;
bool cmp(const Node &a, const Node &b) {
return pos[a.l] == pos[b.l] ? a.r < b.r : pos[a.l] < pos[b.l];
}

int a
;
map<int, int> ma;
Node query
;
int res
;

void add(int x) {
ma[x]++;
}

void rem(int x) {
if (ma[x]-- == 1) {
ma.erase(x);
}
}

int solve(int x) {
map<int, int>::iterator it = ma.upper_bound(x);
return it == ma.end() ? NEXIST : it->fi;
}

int main() {
int t, n, m;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", a+i);
pos[i] = i/blk;
}
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &query[i].l, &query[i].r, &query[i].v);
query[i].id = i;
}
sort(query+1, query+1+m, cmp);

int l = 1, r = 0;
for (int i = 1; i <= m; i++) {
while (r < query[i].r) add(a[++r]);
while (l > query[i].l) add(a[--l]);
while (r > query[i].r) rem(a[r--]);
while (l < query[i].l) rem(a[l++]);
res[query[i].id] = solve(query[i].v);
}

for (int i = 1; i <= m; i++) {
if (res[i] == NEXIST) {
puts("not exist");
} else {
printf("%d\n", res[i]);
}
}
ma.clear();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: