跳到正文

题解

题解:P15802 [GESP202603 七级] 拆分

houzi777约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年3月20日
更新
2026年3月20日
篇幅
约 3 分钟
题目
P15802

版本

  1. v1当前

思路:

首先,每个数都会被分解为 22 和 33,因为如果是其他数,那么可以把他们再次分解,得到更好的结果,所以每个数都要分解为 22 和 33。

那么,对于一个数 n(n≥5)n(n \ge 5),要尽可能的分解 33,除了 44 要分解成 2+22+2 以外,能分解出 33 就要分解,所以对于一个 n(n≥5)n(n \ge 5) 有以下几种情况:

ans={3n3n≡0mod33⌊n3⌋−1×4n≡1mod33⌊n3⌋×2n≡2mod3ans = \begin{cases} 3^{\frac{n}{3}} & n \equiv 0 \hspace{0.1cm} mod \hspace{0.1cm} 3 \\ 3^{\lfloor \frac{n}{3} \rfloor - 1} \times 4 & n \equiv 1 \hspace{0.1cm} mod \hspace{0.1cm} 3 \\ 3^{\lfloor \frac{n}{3} \rfloor} \times 2 & n \equiv 2 \hspace{0.1cm} mod \hspace{0.1cm} 3 \end{cases}

而对于 1∼41 \sim 4,答案就是 nn。

注意事项:

  • 要开long long。
  • 不要忘记对 10910^9 取模。
  • 要写快速幂,不要用pow。
  • 这题是多测。

代码:

C++
#include <bits/stdc++.h>

using namespace std;

#define endl '\n'
#define int long long
const int mod = 1e9;

int fpow(int a, int b) {
	if (b == 0) return 1;
	int ans = fpow(a, b / 2);
	ans = ans * ans % mod;
	if (b & 1) return ans * a % mod;
	else return ans;
}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int T;
	cin >> T;
	while (T--) {
		int n;
		cin >> n;
		if (n <= 4) {
			cout << n << endl;
			continue;
		}
		if (n % 3 == 0) {
			cout << fpow(3, n / 3) % mod << endl;
		} else if (n % 3 == 1) {
			cout << fpow(3, n / 3 - 1) * 4 % mod << endl;
		} else {
			cout << fpow(3, n / 3) * 2 % mod << endl;
		}
	}
	return 0;
}
原文