题解:P7252 [JSOI2011] 棒棒糖

· · 题解

随机化。

题意

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

思路

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

::::success[代码]

#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;
}

::::