hust 1628 LowerBound 莫队算法

题目

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

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

简要题意:找到下标 [L,R] 内大于 V <script type="math/tex" id="MathJax-Element-17">V</script>的最小的数。

题解

没学过莫队的可参考这份题解的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[N];
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[N];
map<int, int> ma;
Node query[N];
int res[N];

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值