Codeforces Round #716 (Div. 2)D. Cut and Stick(莫队维护区间众数)

AC代码:

#include <bits/stdc++.h>
//#define int long long
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=4e5+6;
int n,m,len;
int w[N],ans[N];
int cnt[N],num[N];

struct node{
	int id,l,r;
}q[N];

int get(int x){
	return x/len;
}

bool cmp(node a,node b){
	if(get(a.l)!=get(b.l)) return get(a.l)<get(b.l);
	return a.r<b.r;
}

void add(int x,int &res){
	int k=cnt[x];
	cnt[x]++;
	num[k]--;
	num[k+1]++;
	res=max(res,cnt[x]);
}

void del(int x,int &res){
	int k=cnt[x];
	cnt[x]--;
	num[k]--;
	num[k-1]++;
	if(res==k&&num[k]==0)res--;
}

main(){
	cin>>n>>m,len=sqrt(n);
	for(int i=1;i<=n;i++)cin>>w[i];
	
	for(int i=0;i<m;i++){
		int l,r;
		cin>>l>>r;
		q[i]={i,l,r};
	}
	
	sort(q,q+m,cmp);
	
	int res=0;
	for(int k=0,i=0,j=1;k<m;k++){
		int id=q[k].id,l=q[k].l,r=q[k].r;
		while(i<r)add(w[++i],res);
		while(i>r)del(w[i--],res);
		while(j>l)add(w[--j],res);
		while(j<l)del(w[j++],res);
		
		int other=r-l+1-res;
		ans[id]=max(1,res-other);
	}
	
	for(int i=0;i<m;i++)cout<<ans[i]<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值