莫队算法 模板题 小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)。