莫队算法 模板题 小Z的袜子 洛谷 P1494

26 篇文章 0 订阅
15 篇文章 0 订阅

莫队算法 模板题 小Z的袜子 洛谷 P1494

附上题目链接 https://www.luogu.org/problem/P1494

附上我的莫队启蒙链接 https://oi-wiki.org/misc/mo-algo/

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 5e4 + 7;
int n, m;
ll b;
int c[maxn], pos[maxn], mark[maxn]; //mark记录对于此位置的每一种颜色的总数
ll ans = 0;
struct problem
{
    int l, r, id;
    ll a, b;
    bool operator<(const problem x) const
    {
        return pos[l] == pos[x.l] ? r < x.r : l < x.l;
        //注意此处,当l相同时,一定相同,但是当块号不同时,l一定不同
    }
} pro[maxn];
bool cmp(problem x, problem y)
{
    return x.id < y.id;
}

void add(int i)
{
    ans += mark[c[i]];
    mark[c[i]]++;
}
void del(int i)
{
    mark[c[i]]--;
    ans -= mark[c[i]];
}
//每一次add和del都会修改mark[]数组的值
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
int main()
{
    scanf("%d %d", &n, &m);
    memset(mark, 0, sizeof(mark));
    memset(pos, 0, sizeof(pos));
    b = sqrt(n); //分块开始,b为分块出来的大小
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &c[i]);
        pos[i] = i / b; //所分块的位置,即块的编号
    }
    for (int i = 1; i <= m; i++)
    {
        scanf("%d %d", &pro[i].l, &pro[i].r);
        pro[i].id = i;
    }
    sort(pro + 1, pro + 1 + m); //进行分块排序
    //进行完分块排序之后,虽然并没有对原本的数组有什么改变,但对于问题我们可以通过递推来进行求解了
    int l = 1, r = 0;
    for (int i = 1; i <= m; i++)
    {
        while (l < pro[i].l)
            del(l++);
        while (l > pro[i].l)
            add(--l);
        while (r > pro[i].r)
            del(r--);
        while (r < pro[i].r)
            add(++r);
        pro[i].a = ans; //能获得的答案
        ll x = pro[i].r - pro[i].l + 1;
        pro[i].b = x * (x - 1) / 2; //这个区间内的所有情况
    }
    sort(pro + 1, pro + 1 + m, cmp);
    for (int i = 1; i <= m; i++)
    {
        ll xa = pro[i].a, xb = pro[i].b, gcdx = gcd(xa, xb);
        if (xa == 0)
            printf("0/1\n");
        else
            printf("%lld/%lld\n", xa / gcdx, xb / gcdx);
    }
    return 0;
}
//莫队算法的时间复杂度为n*√n,但本题的时间复杂度为O((N+M)*√N)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值