zoukankan      html  css  js  c++  java
  • HDU 6534 莫队+ 树状数组

    题意及思路:https://blog.csdn.net/tianyizhicheng/article/details/90369491

    代码:

    #include <bits/stdc++.h>
    #define lowbit(x) (x & (-x))
    using namespace std;
    const int maxn = 30010;
    int c[maxn * 3], num[maxn], b[maxn * 3], lb[maxn], rb[maxn], a[maxn];
    int ans[maxn], tot;
    struct Query {
    	int l, r, id;
    	bool operator < (const Query& rhs) const {
    		if(num[l] == num[rhs.l]) return r < rhs.r;
    		return num[l] < num[rhs.l];
    	}
    };
    Query q[maxn];
    void add(int x, int y) {
    	for (; x <= tot; x += lowbit(x)) {
    		c[x] += y;
    	}	
    }
    int query(int x) {
    	int ans = 0;
    	for (; x; x -= lowbit(x)) {
    		ans += c[x];
    	}
    	return ans;
    } 
    int main() {
    	int n, m, k;
    	scanf("%d%d%d", &n, &m, &k);
    	for (int i = 1; i <= n; i++) {
    		scanf("%d", &a[i]);
    		b[++tot] = a[i], b[++tot] = a[i] + k, b[++tot] = a[i] - k - 1;
    	}
    	sort(b + 1, b + 1 + tot);
    	tot = unique(b + 1, b + 1 + tot) - (b + 1);
    	for (int i = 1; i <= n; i++) {
    		lb[i] = lower_bound(b + 1, b + 1 + tot, a[i] - k - 1) - b;
    		rb[i] = lower_bound(b + 1, b + 1 + tot, a[i] + k) - b;
    		a[i] = lower_bound(b + 1, b + 1 + tot, a[i]) - b;
    	}
    	for (int i = 1; i <= m; i++) {
    		scanf("%d%d", &q[i].l, &q[i].r);
    		q[i].id = i;
    	}
    	int len = sqrt(n);
    	for (int i = 1; i <= n; i++) {
    		num[i] = (i - 1) / len + 1;
    	}
    	sort(q + 1, q + 1 + m);
    	int l = q[1].l, r = q[1].l - 1, sum = 0;
    	for (int i = 1; i <= m; i++) {
    		while(r < q[i].r) {
    			r++;
    			sum += query(rb[r]) - query(lb[r]);
    			add(a[r], 1);
    		}
    		while(l > q[i].l) {
    			l--;
    			sum += query(rb[l]) - query(lb[l]);
    			add(a[l], 1);
    		}
    		while(r > q[i].r) {
    			add(a[r], -1);
    			sum -= query(rb[r]) - query(lb[r]);
    			r--;
    		}
    		while(l < q[i].l) {
    			add(a[l], -1);
    			sum -= query(rb[l]) - query(lb[l]);
    			l++;
    		}
    		ans[q[i].id] = sum;
    	}
    	for (int i = 1; i <= m; i++)
    		printf("%d
    ", ans[i]);
    }
    

      

  • 相关阅读:
    linux 6 安装 Nagios服务
    linux 6 安装 Nginx服务
    Rsync的配置与使用
    linux 6 搭建 msyql 服务
    linux6搭建Apache服务
    Linux 7搭建NFS服务
    Linux 6 忘记root密码重置
    简单makefile
    多线程c++11编程题目
    redis 代码结构与阅读顺序
  • 原文地址:https://www.cnblogs.com/pkgunboat/p/10935369.html
Copyright © 2011-2022 走看看