我不知道题解应该叫什么名字
我不知道啊,看到出现次数我就来了。
首先,不存在绝对众数的话答案一定为
反之,我们尝试去构造答案。
显然,一个绝对众数带一个别的数一定是不劣的。
那么,就让剩下的部分独立一组就好了。
即答案为绝对众数数量减去其他数数量。
考虑这需要我们实现什么功能:查询一段区间内是否有数,如果有,输出其值,保证只有一个。
直接莫队套分块,对出现次数分块即可。
:::success[代码]
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5;
int belong[N],a[N],ans[N];
struct node{int l,r,id;}b[N];
struct item{//对出现次数分块
static const int M=1000;
int belong[N],st[M],ed[M];
int a[N],cnt[N],sum[M],block,num;
inline void init(int n){
block=(int)sqrt(n);num=n/block;
for(int i=1;i<=n;i++){
belong[i]=i/block;ed[belong[i]]=i;
if(st[belong[i]]==0) st[belong[i]]=i;
}
}
inline void add(int x){
if(cnt[x]!=0) sum[belong[cnt[x]]]--,a[cnt[x]]--;
cnt[x]++;a[cnt[x]]++;sum[belong[cnt[x]]]++;
}
inline void del(int x){
sum[belong[cnt[x]]]--;a[cnt[x]]--,cnt[x]--;
if(cnt[x]!=0) sum[belong[cnt[x]]]++,a[cnt[x]]++;
}
inline int ask(int x){//查询 x 到 n 是否有值
int id=-1;
for(int i=x;i<=ed[belong[x]];i++) if(a[i]) return i;//散块
for(int i=belong[x]+1;i<=num;i++) if(sum[i]){id=i;break;}//整块
if(id==-1) return 0;//不存在
for(int i=st[id];i<=ed[id];i++) if(a[i]) return i;//遍历存在答案的整块
}
}Block;
inline int read(){
int s=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)) s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*f;
}
inline bool operator < (node x,node y){
if(belong[x.l]!=belong[y.l]) return belong[x.l]<belong[y.l];
return ((belong[x.l]&1)?(x.r<y.r):(x.r>y.r));
}
signed main(){
int n,m;cin>>n>>m;
int block=(int)sqrt(n);Block.init(n);
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<=n;i++) belong[i]=i/block;
for(int i=1;i<=m;i++) b[i]={read(),read(),i};
sort(b+1,b+m+1);int l=1,r=0;
for(int i=1;i<=m;i++){
while(l>b[i].l) l--,Block.add(a[l]);
while(r<b[i].r) r++,Block.add(a[r]);
while(l<b[i].l) Block.del(a[l]),l++;
while(r>b[i].r) Block.del(a[r]),r--;
int len=b[i].r-b[i].l+1;
int now=Block.ask(len/2+(len%2!=0)+1);
if(now==0) ans[b[i].id]=1;//不存在绝对众数
else ans[b[i].id]=now-(len-now);//绝对众数数量-其他数数量
}
for(int i=1;i<=m;i++) cout<<ans[i]<<"\n";
return 0;
}
:::