HDU 3874 Necklace

时间:2022-02-03 23:46:35

莫队算法。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std; const int maxn = + ;
int n, m;
int a[maxn],pos[maxn],cnt[+];
long long ans[+], Ans;
int L, R;
struct X
{
int l, r, id;
}s[+]; bool cmp(const X&a, const X&b)
{
if (pos[a.l] == pos[b.l]) return a.r < b.r;
return a.l < b.l;
} int main()
{
int T; scanf("%d",&T);
while (T--)
{
memset(cnt,,sizeof cnt);
scanf("%d", &n);
int sz = sqrt(n);
for (int i = ; i <= n; i++)
{
pos[i] = i / sz;
scanf("%d", &a[i]);
} scanf("%d", &m);
for (int i = ; i <= m; i++) {
scanf("%d%d", &s[i].l, &s[i].r);
s[i].id = i;
}
sort(s + , s + + m, cmp);
Ans=;
for (int i = s[].l; i <= s[].r; i++)
{
cnt[a[i]]++;
if(cnt[a[i]]==) Ans=Ans+(long long)a[i];
}
ans[s[].id] = Ans; L = s[].l; R = s[].r; for (int i = ; i <= m; i++)
{
while (L < s[i].l)
{
cnt[a[L]]--;
if(cnt[a[L]]==) Ans=Ans-(long long)a[L];
L++;
}
while (L > s[i].l)
{
L--;
cnt[a[L]]++;
if(cnt[a[L]]==) Ans=Ans+(long long)a[L];
}
while (R < s[i].r)
{
R++;
cnt[a[R]]++;
if(cnt[a[R]]==) Ans=Ans+(long long)a[R];
}
while (R > s[i].r)
{
cnt[a[R]]--;
if(cnt[a[R]]==) Ans=Ans-(long long)a[R];
R--;
}
ans[s[i].id] = Ans;
} for (int i = ; i <= m; i++) printf("%lld\n", ans[i]);
}
return ;
}