跳到正文

题解

ZJU 2026 Contest7 C - Mei Ti Le 07.15 【贪心 + 递归】

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

文章信息

发布
2026年7月15日
收录
2026年7月15日
更新
2026年11月13日
篇幅
约 5 分钟

版本

  1. v1当前

原题链接:https://codeforces.com/gym/704574/problem/C

思路

要求删除最少的数,使得剩下的数中不存在两个不同的数 x, y 满足:

代码
x + y = k^p  (p >= 1)

初始集合为:

代码
{1, 2, ..., n}

考虑当前还没有处理的区间 [1, n]。

令 P 为当前满足:

代码
P < 2n

的最大 k 的正整数次幂。

因为两个不同的数最大和为:

代码
n + (n - 1) = 2n - 1

所以只需要考虑 P < 2n 的幂。

对于固定的 P,所有满足:

代码
x + y = P
x < y
1 <= x, y <= n

的数对中,较小数 x 的范围为:

代码
max(1, P - n) <= x <= (P - 1) / 2

记:

C++
L = max(1, P - n)
R = (P - 1) / 2

这些数对互不相交,因此至少要删除每对中的一个数。

贪心地删除每一对中较小的数,即删除区间 [L, R],贡献:

C++
R - L + 1

删除这些数后,剩下还可能产生冲突的只在:

代码
[1, L - 1]

于是令:

C++
n = L - 1

继续处理即可。

如果最小的幂 k 都满足:

代码
k >= 2n

则当前区间内任意两个不同数的和都小于 k,不可能再产生冲突,结束。


代码

C++
#include<bits/stdc++.h>
#define sz(a) int((a).size())
#define pii pair<int, int>
#define all(a) (a).begin(), (a).end()
using namespace std;
using ll = long long; 
using ull = unsigned long long; 
const ll inf = (1ll << 60);
const int M = 1e6+5;
const double PI = acos(-1);

template<class A> string to_string(const A& v) {
	string s = "{";
	for (const auto& x : v) s += ((s).size() > 1 ? ", " : "") + to_string(x);
	return s += "}";    
}
template<class A, class B> string to_string(const pair<A, B>& p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
void debug_out() { cerr << '\n'; }

template<class T, class... U>
void debug_out(const T& x, const U&... args) {
	cerr << ' ' << to_string(x);
	debug_out(args...);
}
// 91: red 93: yellow 96: blue
#define sc(x) cerr << "\033[" << x << "m" 
#define debug(...) //sc(96), cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__), sc(39)

/*
思路:
每一次递归找当前可达最大幂次 ( < 2*n )
删除每一对相加等于该幂次的两个数中的较小数 ( 删 [ L, R ] : R - L + 1 个 )
递归寻找下一段 [ 1, L-1 ]
*/

void work(){
	ll n, k;
	cin >> n >> k;
	ll ans = 0, up = 2 * n;
	if(k == 1 || k >= up){
		cout << "0\n";
		return;
	}
	debug(n, k);

	ll mxp = k;
	while((__int128)mxp * k < up){
		mxp *= k;
	}
	debug(up, mxp, n, k);
	while(true){
		// 最大幂次 mxp
		up = 2 * n;
		if(k >= up) break;
		while(mxp >= up){
			mxp /= k;
		}
		debug(up, mxp, n, k);

		// 最大幂次 = x + y 对应的较小数 x
		ll L = max(1ll, mxp - n);
		ll R = (mxp - 1) / 2;
		debug(L, R);
		ans += max(0ll, R - L + 1);

		ll curn = L - 1;
		if(curn <= 0) break;
		n = curn;
		debug(ans);
		// mxp /= k;
	}
	cout << ans << '\n';
}

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int T = 1;
	cin >> T;
	while(T--) work();
}
/*

*/

复杂度

每次处理都会使 n 缩小,并且 mxp 只会不断除以 k。

因此每组测试用例复杂度为:

代码
O(log_k n)

在 n, k <= 10^18 的范围内可以通过。

原文