题意
- P=p1p2p3…pn
- p1,p2,p3,…,pn 不同
- 给出 k ,求第n大的p
输入 n,k(1<=k<=8,1<=n<=105)
输出答案满足限制条件k下的第n大的p的数值
Sample Input | Sample Output |
---|---|
10000 1 | 104327 |
10000 2 | 41073 |
10000 3 | 51382 |
10000 4 | 135555 |
题解
思路是离线去做,直接打表
n=105,k=1,2,…,8
的答案,同时也得到了
n<105
的答案
用dfs,求出p的组合,注意剪支
我开了 O2 优化是 3.506 s
#pragma GCC optimize ("O2")
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAXN=1e5+50;
const int TOP=1e6+3e5;
int res[MAXN],n,k,o;LL dat[MAXN][8];bool prim[TOP];
const int nn[8]={100000,25000,8000,5000,5000,3000,1000,590};//好像不加这个也就慢了1s
int tag[8];
void init(){
for(int i=2;i*i<TOP;i++)
if(!prim[i]) for(int j=i*i;j<TOP;j+=i)
prim[j]=1;
o=0;for(int i=2;i<TOP;i++) if(!prim[i]) res[o++]=i;
// printf("prim num:%d\n",o);
}
priority_queue<LL,vector<LL>,less<LL> > que;
void dfs(int now,int cnt,LL num){
if(cnt==k){
if(que.size()<100000) que.push(num);
else if(que.top()>num) que.push(num),que.pop();
return ;
}
if((que.size()==100000&&num*pow((LL)res[now],k-cnt)>=que.top())||now>n) return ;
dfs(now+1,cnt+1,num*res[now]);
dfs(now+1,cnt,num);
}
void work(){
init();
for(int i=1;i<=100000;i++) dat[i][0]=res[i-1];
for(k=2;k<=8;k++){
n=nn[k-1];
dfs(0,0,1);
while(!que.empty()){
dat[que.size()][k-1]=que.top();
que.pop();
}
}
}
int main()
{
work();
while(scanf("%d%d",&n,&k)!=EOF){
printf("%lld\n",dat[n][k-1]);
}
return 0;
}
//代码正确性未经验证