跳到正文

题解

题解:P15240 [NHSPC 2025] 解码密钥

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

文章信息

收录
2026年2月9日
更新
2026年2月9日
篇幅
约 3 分钟
题目
P15240

版本

  1. v2当前
  2. v1

题意

求第 nn 个能被 pp 数组中的至少一个正整数整除的正整数。

分析

首先我们可以注意到 1≤n≤1091\le n\le10^9,我们就不可能吧这 nn 个数全都枚举出来。

然后就是 1≤k≤61\le k\le 6,可以猜到复杂度是 kk 的指数级的。

我们又发现答案 ≤1018\le10^{18},所以我们考虑二分。

现在问题又变成了在一定值以内求满足要求的数有几个。

这个时候就可以使用容斥原理,我们要求的值可以表示为:

∑i=1k⌊xpi⌋−∑1≤i<jk⌊xlcm⁡(pi,pj)⌋+∑1≤i<j<lk⌊xlcm⁡(pi,pj,pl)⌋−⋯+(−1)k+1⌊xlcm⁡(p1,p2,…,pk)⌋\sum_{i=1}^k \left\lfloor \frac{x}{p_i} \right\rfloor - \sum_{1 \le i < j}^{k} \left\lfloor \frac{x}{\operatorname{lcm}(p_i, p_j)} \right\rfloor + \sum_{1 \le i < j < l}^{k} \left\lfloor \frac{x}{\operatorname{lcm}(p_i, p_j, p_l)} \right\rfloor - \cdots + (-1)^{k+1} \left\lfloor \frac{x}{\operatorname{lcm}(p_1, p_2, \dots, p_k)} \right\rfloor

可以写成:

∑S⊆{1,…,k}S≠∅(−1)∣S∣+1⌊xlcm⁡{pi:i∈S}⌋\sum_{\substack{S \subseteq \{1,\dots,k\} \\ S \neq \varnothing}} (-1)^{|S|+1} \left\lfloor \frac{x}{\operatorname{lcm}\{p_i : i \in S\}} \right\rfloor

解法

先二分,对于问题在一定值以内满足要求的数有几个,只需要枚举集合 SS,就可以解决,然后将求出来的值与二分的 midmid 值比较即可。

算一下时间复杂度,二分 O(log⁡n)O(\log_{n}),检查 O(2k)O(2^{k}),合起来 O(2klog⁡n)O(2^{k}\log_{n} ) 可以通过。

记得开 long long。

代码

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int x,int y){
	if(x<y){
		swap(x,y);
	}
	int r = x%y;
	while(r){
		x = y;
		y = r;
		r = x%y;
	}
	return y;
}
int lcm(int x,int y){
	return x/gcd(x,y)*y;
}
int p[10];
signed main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int n,k,s,l=1,r=1e18,res=1e18;
    cin>>n>>k;
    s = (1<<k)-1;
    for(int i=1;i<=k;i++){
    	cin>>p[i];
	}
	while(l<=r){
		int mid=(l+r)>>1,ans=0;
		for(int t=1;t<=s;t++){
			int bits=0,cnt=1;
			for(int i=1;i<=k;i++){
				if(t&(1<<(i-1))){
					bits++;
					cnt = lcm(cnt,p[i]);
				}
			}
			int d = mid/cnt;
			if(bits%2){
				ans+=d;
			}else{
				ans-=d;
			}
		}
		if(ans>=n){
			res = mid;
			r = mid-1;
		}else{
			l = mid+1;
		}
	}
	cout<<res;
    return 0;
}
原文