#bzoj 2038 莫队算法

bzoj 2038 莫队算法

@(E ACMer)


题目抽象
给定 nn<50000 个数,和 q(q<50000) 个询问,每个询问是 [L,R] 区间,问在这个区间中任意选两个数,选到相同的数的概率是多少?

思路分析
- 首先容易有概率的数学公式:

2a+2b+...+2x2rl+1
化简得到:
a2+b2+...+x2(a+b+....+x)(rl+1)(rl)

- 这时候利用莫队算法维护区间内各种数的平方和和各种数的数值和即可。

注意
- wa了一次因为没有删除文件输入。


code

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;


struct node {
    int l, r, id;
}Q[int(5e4+ 9)];

int n, q, a[int(5e4 + 9)];
int lefts, rights;
long long ans, out1[int(5e4 + 9)], cnt[int(5e4 +9)], out2[int(5e4 + 9)];


bool cmp(const node& A, const node& B) {
    int bs =   int(0.1 *sqrt(n));
    if (A.l / bs == B.l / bs) return A.r / bs < B.r / bs;
    return A.l / bs < B.l / bs;
}

void del(int x) {
    ans -= cnt[x] * cnt[x];
    cnt[x]--;
    ans += cnt[x] * cnt[x];
    ans++;
}


void add(int x) {
    ans -= cnt[x] * cnt[x];
    cnt[x]++;
    ans += cnt[x] * cnt[x];
    ans--;
}

long long gcd(long long a, long long b) {
    if (!b) return a;
    return gcd(b, a % b);
}

int main()
{
    //freopen("in.txt", "r", stdin);
    while (~scanf("%d%d", &n, &q)) {
        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
        }
        for (int i = 0; i < q; i++) {
            scanf("%d%d", &Q[i].l, &Q[i].r);
            //Q[i].l--;
            Q[i].id = i;
        }
        lefts = 1, rights = 0, ans = 0;
        sort(Q, Q + q, cmp);
        for (int i = 0; i < q; i++) {
            while (lefts < Q[i].l) del(a[lefts++]);
            while (lefts > Q[i].l) add(a[--lefts]);
            while (rights < Q[i].r) add(a[++rights]);
            while (rights > Q[i].r) del(a[rights--]);
            out1[Q[i].id] = ans;
            out2[Q[i].id] = (long long)(rights - lefts + 1) * (rights - lefts);
        }
        for (int i = 0; i < q; i++) {
            if (!out1[i] || !out2[i]) {
                puts("0/1");
            } else {
                long long g = gcd(out1[i], out2[i]);
                printf("%lld/%lld\n", out1[i] / g, out2[i] / g);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值