• 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]);
    }
    

      

  • 相关阅读:
    mysql8下载安装及配置
    jdk11下载安装及环境变量配置
    展示所有商品案例
    事务(转账实例)
    Part2.7 ESLint
    Part2.6 Webpack
    Part2.5 模块化开发
    Part2.4 gulp 实践
    Part2.3 Grunt
    Part2.2 plop 使用
  • 原文地址:https://www.cnblogs.com/pkgunboat/p/10935369.html
Copyright © 2020-2023  润新知