zoukankan      html  css  js  c++  java
  • 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
    ", ans[i]);
    
    	return 0;
    }
    
    
  • 相关阅读:
    [开发笔记]-使用bat命令来快速安装和卸载Service服务
    [开发笔记]-多线程异步操作如何访问HttpContext?
    [开发笔记]-Windows Service服务相关注意事项
    [开发笔记]-VS2012打开解决方案崩溃或点击项目崩溃
    Chrome 开发者工具有了设备模拟器
    Mysql查看数据库表容量大小
    golang操作mysql数据库
    golang命令和VSCode配置
    golang广度优先算法-走迷宫
    golang爬取免费代理IP
  • 原文地址:https://www.cnblogs.com/AOQNRMGYXLMV/p/6945679.html
Copyright © 2011-2022 走看看