跳到正文

题解

题解:P7252 [JSOI2011] 棒棒糖

正负君约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年10月19日
收录
2026年10月19日
更新
2026年11月11日
篇幅
约 2 分钟
题目
P7252

版本

  1. v1当前

随机化。

题意

给定一个长为 nn 的序列 aa,询问 mm 次,每次询问 [l,r][l,r] 内的绝对众数。

思路

若存在绝对众数,则在 [l,r][l,r] 随机取一个数能取到的概率为 12\frac 1 2,取 kk 次还取不到的概率是 12k\frac 1{2^k},我们认定它没有绝对众数,这里 k=30k=30。复杂度为 O(mklog⁡n)O(mk\log n)。

代码
C++
#include<iostream>
#include<algorithm>
#include<vector>
#include<random>
#include<chrono>
using namespace std;
const int N=5e4+10,k=30;
int n,m,a[N];
vector<int>buc[N];
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
int calc(int l,int r,int x)
{
  return upper_bound(buc[x].begin(),buc[x].end(),r)-lower_bound(buc[x].begin(),buc[x].end(),l);
}
signed main()
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin>>n>>m;
  for(int i=1; i<=n; ++i)
  {
    cin>>a[i];
    buc[a[i]].push_back(i);
  }
  while(m--)
  {
    int l,r;
    bool flag=false;
    cin>>l>>r;
    for(int i=1; i<=k; ++i)
    {
      int pos=l+rnd()%(r-l+1);
      int cnt=calc(l,r,a[pos]);
      if(cnt*2>r-l+1)
      {
        cout<<a[pos]<<'\n';
        flag=true;
        break;
      }
    }
    if(!flag)cout<<"0\n";
  }
  return 0;
}
原文