[SDOI2009]HH的项链(莫队)

本文深入探讨了莫队算法的原理与应用,通过离线处理和区间查询优化,实现高效的区间统计。提供了完整的C++代码示例,适用于解决大规模数据集上的区间问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嘟嘟嘟

这题原本莫队能过,自从某谷加强数据后好像就只能80了。
但这并不重要。
(其实写这篇博客只是想记录一下莫队板子)

莫队,总而言之,离线,排序,暴力。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e5 + 5;
const int maxN = 1e6 + 5;
inline ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
inline void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

int n, m, S, a[maxn];
int tot[maxN], ans[maxn], cnt = 0;
struct Node
{
  int L, R, id, b;
  bool operator < (const Node& oth)const
  {
    return b < oth.b || (b == oth.b && R < oth.R);
  }
}q[maxn];

int main()
{
  n = read(); S = sqrt(n);
  for(int i = 1; i <= n; ++i) a[i] = read();
  m = read();
  for(int i = 1, L, R; i <= m; ++i)
    {
      L = read(); R = read();
      q[i] = (Node){L, R, i, (L - 1) / S + 1};
    }
  sort(q + 1, q + m + 1);
  for(int i = 1, l = 0, r = 0; i <= m; ++i)
    {
      while(l < q[i].L) if(!--tot[a[l++]]) cnt--;
      while(l > q[i].L) if(!tot[a[--l]]++) cnt++;
      while(r < q[i].R) if(!tot[a[++r]]++) cnt++;
      while(r > q[i].R) if(!--tot[a[r--]]) cnt--;
      ans[q[i].id] = cnt;
    }
  for(int i = 1; i <= m; ++i) write(ans[i]), enter;
  return 0;
}

转载于:https://www.cnblogs.com/mrclr/p/10077153.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值