CodeForces 522D Closest Equals 树状数组

题意:

给出一个序列\(A\),有若干询问。
每次询问某个区间中值相等且距离最短的两个数,输出该距离,没有则输出-1.

分析:

\(pre_i = max\{j| A_j = A_i, j < i\}\),也就是前一个与\(A_i\)相等的数字的下标。
这个可以通过对序列排序,数值相等按照下标排序来计算。
将询问离线,按照询问区间的右端点从左到右排序。
从左到右扫描,向树状数组中在位置\(pre_i\)插入\(i - pre_i\),并维护一个后缀最小值。

查询的时候直接查即可。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
#define REP(i, a, b) for(int i = a; i < b; i++)
#define PER(i, a, b) for(int i = b - 1; i >= a; i--)
#define SZ(a) ((int)a.size())
#define MP make_pair
#define PB push_back
#define EB emplace_back
#define ALL(a) a.begin(), a.end()
typedef long long LL;
typedef pair<int, int> PII;

const int maxn = 500000 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
inline int lowbit(int x) { return x&(-x); }
int C[maxn];

void upd(int& a, int b) { if(a > b) a = b; }

void update(int x, int v) {
    while(x) {
        upd(C[x], v);
        x -= lowbit(x);
    }
}

int query(int x) {
    int ans = INF;
    while(x <= n) {
        upd(ans, C[x]);
        x += lowbit(x);
    }
    if(INF == ans) ans = -1;
    return ans;
}

struct Query
{
    int l, r, id;
    bool operator < (const Query& t) const {
        return r < t.r;
    }
};

PII a[maxn];
int ans[maxn], pre[maxn];
Query q[maxn];

int main() {
    scanf("%d%d", &n, &m);
    memset(C, 0x3f, sizeof(C));
    REP(i, 1, n + 1) {
        scanf("%d", &a[i].first);
        a[i].second = i;
    }
    sort(a + 1, a + 1 + n);
    REP(i, 2, n + 1) {
        if(a[i].first == a[i-1].first)
            pre[a[i].second] = a[i-1].second;
    }
    REP(i, 0, m) {
        scanf("%d%d", &q[i].l, &q[i].r);
        q[i].id = i;
    }
    sort(q, q + m);

    int p = 1;
    REP(i, 0, m) {
        for( ;p <= q[i].r; p++) {
            if(pre[p]) update(pre[p], p - pre[p]);
        }
        ans[q[i].id] = query(q[i].l);
    }

    REP(i, 0, m) printf("%d\n", ans[i]);

    return 0;
}

转载于:https://www.cnblogs.com/AOQNRMGYXLMV/p/6945679.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值