题解:P15240 [NHSPC 2025] 解码密钥
JChen_anty
·
·
题解
题目大意
给定正整数 n 和 k 个密钥 p_1,p_2, \dots,p_k,求第 n 个能被至少一个密钥整除的正整数。
数据范围:1 \le n \le 10^9,1 \le k \le 6,答案不超过 10^{18}。
思路
注意到 k\le6。
因此考虑枚举被 p_1,p_2, \dots,p_k 中若干个数整除的所有可能,至多有 2^6-1=63 种可能。
题目要求第 n 个满足条件的数,考虑二分答案,右端点为 \min(n\times\min(p_i),10^{18})。
二分单调性的证明
定义判定函数 f(x) 为“区间 [1,x] 内能被至少一个密钥整除的正整数数量。”
对于任意两个正整数 x_1<x_2,区间 [1,x_1] 是 [1,x_2] 的真子集。因此 [1,x_1] 内的有效数必然全部包含在 [1,x_2] 内,且 [x_1+1,x_2] 可能新增有效数。
即
## 代码
```cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
int lcm(int a,int b){
if(a==0||b==0)return 0;
return a/__gcd(a,b)*b;
}
// 统计[1,x]内有效数的数量
// p: 去重后的密钥数组,x: 右边界
int cnt_v(int x, const vector<int>& p) {
int c=0; // 有效数总数
int k=p.size(); // 去重后的密钥数量
// 枚举所有非空子集
for(int mask=1;mask<(1<<k);++mask) {
int cl=1; // cl: 当前子集的最小公倍数
int b=0; // b: 当前子集的元素个数
bool of=0; // of: 溢出标记(lcm超过x则无贡献)
// 遍历每个密钥,判断是否在当前子集
for(int i=0;i<k;++i)
if(mask&(1<<i)){
b++;
cl=lcm(cl,p[i]);
if(cl>x){ // lcm超过x,该子集无贡献
of=1;
break;
}
}
if(of)continue;
// 容斥:奇数个元素加,偶数个元素减(抵消重复计数)
if(b%2==1)c+=x/cl;
else c-=x/cl;
}
return c;
}
// n: 目标序号,p: 原始密钥数组(会预处理)
int erfen(int n,vector<int>& p){
// 预处理:去重+去0
sort(p.begin(),p.end());
p.erase(unique(p.begin(),p.end()),p.end());
p.erase(remove(p.begin(),p.end(),0),p.end());
//由于k极小,这里直接用vector自带的函数
int mn_p=LLONG_MAX;
for(int num:p)mn_p=min(mn_p, num);
int l=1, r=min(n*mn_p,(int)1e18);
int res=r;
while(l<=r){
int m=l+(r-l)/2;
int c=cnt_v(m,p); // 统计[1,m]有效数数量
if(c>=n){
res=m;
r=m-1;
}else
l=m+1;
}
return res;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,k;
cin>>n>>k;
vector<int> p(k);
for(int i=0;i<k;++i)cin>>p[i];
cout<<erfen(n,p)<<endl;
return 0;
}
```
## 复杂度分析
- 时间复杂度:
$O(2^k
\cdot\log\text{ans}),k≤6$,子集枚举仅63次,二分约60次,效率极高。
- 空间复杂度:$O(k)$,仅存储密钥数组与临时变量。
## 注意事项
- ~~十年OI一场空,不开long long见祖宗。~~
- 二分时,计算 $\operatorname{lcm}$ 时注意运算顺序。