跳到正文

题解

ABC470C均摊分析+暴力set

cspjtos约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年8月8日
收录
2026年8月10日
更新
2026年8月24日
篇幅
约 4 分钟

版本

  1. v1当前

背景

完蛋了,C 做不出来了……

这么精(bian)彩(tai)的题一定要来一篇题解……

好久没写过 C 的题解了……

题目传送门

洛谷,AtCoder。

正文

第一种思路

我的考场思路。

维护答案 ansans。

首先看到第一种操作,选择一个点 +1+1。

假设修改了 AxA_x,ansans 变为 ans⊕Ax⊕(Ax+1)ans \oplus A_x \oplus (A_x+1)。

第二种操作,所有非零点集体 −1-1。

维护一个 sum1sum1 表示 ⨁i=1nAi\bigoplus_{i=1}^{n} A_i,sum2sum2 表示 ⨁i=1n(Ai−1)\bigoplus_{i=1}^{n} (A_i-1),ansans 变为 ans⊕sum1⊕sum2ans \oplus sum1 \oplus sum2。

最后 sum1sum1 要更新为 sum2sum2,然后 sum2sum2……

然后就没有然后了……

于是我就卡了 70 分钟,甚至冒出了线段树的想法。

暴力做法

我问老师,这题咋做。

老师:“暴力。”

我 be like。

当我发现操作 2 的确可以暴力 be like。

这道题让我想起来以前一个类似的题也是这样,因为操作 2 次数一定不会超过操作 1,所以可以直接暴力操作 2。

直接用 set 保存操作 1 中发现 >1>1 的位置,操作 2 暴力减即可。

时间复杂度 O(nlogn)O(n log n)。

明明操作有可能循环所有啊

是的,的确单次操作 2 可能循环所有的位置,但是,操作 1 每次只能 +1+1,所以你最多只能增加 qq 次,操作 2 每遍历一个就会 −1-1,但是每个数不能减得比 00 小,总次数自然不会超过操作 1 的执行次数了。

AC Code
C++
#include<iostream>
#include<set>
#define LL long long
#define F(i,k,n) for(int i=(k);i<=(n);++i)
#define RF(i,k,n) for(int i=(k);i>=(n);--i)
using namespace std;
int a[500005];
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int n,q;
	cin>>n>>q;
	int ans=0;
	set<int>st;
	while(q--){
		int op;
		cin>>op;
		if(op==1){
			int x;
			cin>>x;
			ans^=a[x];
			++a[x];
			ans^=a[x];
			if(a[x]>0){
				st.insert(x);
			}
		}else{
			for(auto it=st.begin();it!=st.end();){
				if(a[*it]>1){
					ans^=a[*it];
					--a[*it];
					ans^=a[*it];
					++it;
				}else if(a[*it]==1){
					ans^=1;
					--a[*it];
					it=st.erase(it);
				}else{
					++it;
				}
			}
		}
		cout<<ans<<'\n';
	}
	return 0;
}

评测记录。

提示

set 容器循环的时候删除要记得把新的下一个地址取过来。

原文