跳到正文

题解

题解:P12029 [USACO25OPEN] Election Queries G

HD0X约 6 分钟
原文
文章信息与版本

文章信息

发布
2025年4月14日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 6 分钟
获赞
6
题目
P12029

版本

  1. v1当前

题意略。

令 cic_i 表示第 ii 头牛被投了多少票。首先,如果我们钦定 xx,那么第一个集合中就可以有每头牛的不超过 cxc_x 张票。此后如果要找一个最小的 yy(令 y<xy \lt x),只要它的票数非 0\text{0} 且大于等于整体减 cxc_x 之后的 max⁡i=1nci\max_{i=1}^{n} c_i 就可以单开一组了,这个显然可以线段树二分,于是就有一个 O(qnlog⁡n)O(q n \log n) 的做法了。

发现 cxc_x 的取值最多只有 n\sqrt n 种,所以可以用 set 处理出每个 cxc_x 对应的最大的 xx。但是动态维护这 n\sqrt n 个取值用 set 只能做到O(qnlog⁡2n)O(q \sqrt n \log^2 n),无法通过,所以选择用 unordered_map O(1)O(1) 存迭代器,再用 list O(1)O(1) 删除插入,即可做到 O(qnlog⁡n)O(q \sqrt n \log n)。卡常后可以通过,usaco 上也能过。

C++
#include <bits/stdc++.h>
#pragma optimize("Ofast") 
#pragma target("avx,avx2,fma")
char *p1,*p2,buf[1<<21];
#define getchar() (p1==p2 && (p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
using namespace std;
const int MAXN=2e5+5;
int n,q,a[MAXN],c[MAXN];
int id,x,mx,ans,tot;
set<int>p[MAXN];
list<int>s;
unordered_map<int,list<int>::iterator> iot;
int read()
{
	int x=0;char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x;
}
int write(int x)
{
	if(x>=10) write(x/10);
	putchar(x%10+'0');
}
struct tree{
	int val,add;
}t[MAXN<<2];
void pushup(int rt)
{
	t[rt].val=max(t[rt<<1].val,t[rt<<1|1].val);
}
void build(int l,int r,int rt)
{
	t[rt].add=0;
	if(l==r)
	{
		t[rt].val=c[l];
		return;
	}
	int m=(l+r)>>1;
	build(l,m,rt<<1),build(m+1,r,rt<<1|1);
	pushup(rt);
}
void Pointupdate(int rt,int res)
{
	t[rt].add+=res,t[rt].val+=res;
}
void pushdown(int rt)
{
	if(t[rt].add)
	{
		Pointupdate(rt<<1,t[rt].add);
		Pointupdate(rt<<1|1,t[rt].add);
		t[rt].add=0;
	}
}
void update(int l,int r,int p,int res,int rt)
{
	if(l==r) return Pointupdate(rt,res);
	int m=(l+r)>>1;
	pushdown(rt);
	if(p<=m) update(l,m,p,res,rt<<1);
	else update(m+1,r,p,res,rt<<1|1);
	pushup(rt);
}
int query(int l,int r,int rt)
{
	while(1)
	{
		if(l==r) return l;
		int m=(l+r)>>1;
		pushdown(rt);
		if(t[rt<<1].val+tot>=mx) r=m,rt<<=1;
		else l=m+1,rt=rt<<1|1;
	}
}
signed main()
{
	n=read(),q=read();
	for(int i=1;i<=n;i++) a[i]=read(),++c[a[i]];
	for(int i=1;i<=n;i++)
	{
		if(c[i])
		{
			if(!p[c[i]].size()) s.push_back(c[i]),iot[c[i]]=--s.end();
			p[c[i]].insert(i);
		}
	}
	build(1,n,1);
	while(q--)
	{
		id=read(),x=read();
		p[c[a[id]]].erase(a[id]);
		if(!p[c[a[id]]].size()) s.erase(iot[c[a[id]]]);
		--c[a[id]];
		if(c[a[id]])
		{
			p[c[a[id]]].insert(a[id]);
			if(p[c[a[id]]].size()==1) s.push_back(c[a[id]]),iot[c[a[id]]]=--s.end();
		}
		if(c[x])
		{
			p[c[x]].erase(x);
			if(!p[c[x]].size()) s.erase(iot[c[x]]);
		}
		p[++c[x]].insert(x);
		if(p[c[x]].size()==1) s.push_back(c[x]),iot[c[x]]=--s.end();
		update(1,n,a[id],-1,1);
		update(1,n,x,1,1);
		a[id]=x;ans=0;
		for(int i:s)
		{
			if(i==0 || p[i].empty()) continue;
			tot=i;
			mx=t[1].val;
			if(mx==i) mx=i+1;
			ans=max(ans,abs(*p[i].rbegin()-query(1,n,1)));
		}
		printf("%d\n",ans);
	}
}
原文
存档评论2 条抓取于