D2. Balance (Hard version)(数论/模拟/set)

题目
参考

题意

初始一个空集合,给定q次操作
有3种类型

+ x,表示往集合添加数x
- x,表示往集合中删除数x
? x,表示查询集合中x-mex的元素,x-mex表示第一个能被x整除,且不在集合中的元素。

1<=a<=200000
1<=x<=1e18

思路

hard version,比easy version,多了删数操作。

预处理,统计每个元素x的最大的x-mex。
根据每个元素的最大的x-mex,初始化每个元素x的未出现集合,1,2,3,…,x-mex到集合h[x]。同时每个倍数对应的集合rem[x*i]都添加元素x。

每次新增一个元素,则从h中删去所有与当前元素x相关的次数。

for (auto v: rem[x[i]]) {
	h[v].erase(x[i]/v);
}

每次删除一个元素,则从h中加上所有与当前元素x相关的次数。

for (auto v: rem[x[i]]) {
	h[v].insert(x[i]/v);
}

代码

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pcc pair<char, char>
#define pii pair<int, int>
#define inf 0x3f3f3f3f
#define se second
#define fi first
const int maxn = 200010;
const int mod = 998244353; 

int q;
ll x[maxn];
char op[maxn];
set<ll> st;
map<ll, ll> mp;
map<ll, set<ll>> rem, h;
void solve() {
	cin >> q;
	st.clear();
	mp.clear();
	int cas = 1;
	for (int i = 0; i < q; ++i) {
		cin >> op[i] >> x[i];
//		cout << "case" << cas++ << ":" << endl;
		if (op[i] == '-') {
			continue;
		}
		if (op[i] == '+') {
			st.insert(x[i]);
			continue;
		} 
		ll cur = mp[x[i]];
		if (!cur) {
			cur = 1;
		}
		while (st.find(cur * x[i]) != st.end()) {
			++cur;
		}
		mp[x[i]] = cur;
	}
	// init
	for (auto p: mp) {
		for (int i = 1; i <= p.se; ++i) {
			// h store the set of p.fi, which contains number not been appeared
			h[p.fi].insert(i); 
			// rem store all the factors 
			rem[p.fi * i].insert(p.fi);
		}
	}
	for (int i = 0; i < q; ++i) {
		if (op[i] == '+') { // for + operation, erase all the count of x[i]
			for (auto v: rem[x[i]]) {
				h[v].erase(x[i]/v);
			}
		} else if (op[i] == '-') { // for - operation, insert all the count of x[i]
			for (auto v: rem[x[i]]) {
				h[v].insert(x[i]/v);
			}
		} else {
			cout << x[i] * (*h[x[i]].begin()) << endl;
		}
	}
}
int main() {
	int t = 1;
//	scanf("%d", &t);
	int cas = 1;
	while (t--) {
//		printf("cas %d:\n", cas++);
		solve();	
	}
	
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值