跳到正文

题解

P9463 [EGOI2023] Inflation / 通货膨胀 题解

Eason_cyx约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年5月6日
更新
2026年5月6日
篇幅
约 5 分钟
题目
P9463

版本

  1. v1当前

出了这题的数据,就来写篇题解。

不算太难。

Part 1:42 pts\large\texttt{Part 1:42 pts}

直接模拟,没什么好说的。

时间复杂度 O(qn)O(qn),可以通过前两个 Subtask\text{Subtask}。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[300005];
signed main() {
   ios::sync_with_stdio(false);
   cin.tie(0);
   cout.tie(0);
	int n,Q; cin >> n;
	long long sum = 0;
	for(int i = 1;i <= n;i++) {
		cin >> a[i];
	}
	cin >> Q;
	while(Q--) {
		string opt; cin >> opt;
		if(opt == "INFLATION") {
			int x; cin >> x;
			int ans = 0;
    		for(int i = 1;i <= n;i++) {
    		    a[i] += x;
    		    ans += a[i];
    		}
    		cout << ans << endl;
		}
		else {
			int x,y; cin >> x >> y;
			int ans = 0;
			for(int i = 1;i <= n;i++) {
			    if(a[i] == x) a[i] = y;
			    ans += a[i];
			}
			cout << ans << endl;
		}
	}
	return 0;
}

Record

Part 2:19 pts\large\texttt{Part 2:19 pts}

本部分讲解如何通过子任务 33。

可以发现,要求输出的只是所有价格的总和,而且 xx 是一个固定的值。

每一个元素增加 xx,那么 nn 个元素不就增加了 n×xn \times x 吗?

再加上初始的元素和,可以做到 INFLATION 操作时间复杂度 O(1)O(1)。

于是总时间复杂度降至 O(q)O(q),可以通过。

可以尝试将操作离线下来,和前面的 4242 分结合,得到 6161 分,但是比较麻烦。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[300005];
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
	int n,Q; cin >> n;
	long long sum = 0;
	for(int i = 1;i <= n;i++) {
		cin >> a[i]; sum += a[i];
	}
	cin >> Q;
	while(Q--) {
		string opt; cin >> opt;
		int x; cin >> x;
		sum += n * x;
		cout << sum << endl;
	}
	return 0;
}

Record

Part 3:100 pts\large\texttt{Part 3:100 pts}

我们现在已经知道了怎么快速完成 INFLATION 操作,那 SET 呢?

其实一样啊!把 xx 变成了 yy,不就增加了 y−xy-x 吗?

那怎么统计有多少个值为 xx 的呢?

我们用一个桶来存储就可以了。

最后,在加完以后,记得将桶更新,原来所有的 xx 都变成了 yy。

注意 x=yx=y 的特殊情况!

至此,本题就完成了。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
map<long long,long long> mp;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
	int n,Q; cin >> n;
	long long sum = 0,add = 0;
	for(int i = 1;i <= n;i++) {
		long long x; cin >> x; mp[x]++;
		sum += x;
	}
	cin >> Q;
	while(Q--) {
		string opt; cin >> opt;
		if(opt == "INFLATION") {
			int x; cin >> x;
			add += x;
			sum += 1ll * n * x;
			cout << sum << endl;
		}
		else {
			int x,y; cin >> x >> y;
			x -= add; y -= add;
			int cha = y - x;
			sum += 1ll * mp[x] * cha;
			if(x != y) {
				mp[y] += mp[x];
				mp[x] = 0;
			}
			cout << sum << endl;
		}
	}
	return 0;
}

AC Record

Part 4\large\texttt{Part 4}

总结:这题考察的是桶的思想,以及一点点贡献法,有一定的思维难度,建议评黄。

原文