Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1178
Topic
The perfect number is that its prime factor is only 2, 3, 5, 7, or none. What is the nth perfect number?
Ideas
The smallest perfect number is 1, and then multiply each perfect number by 2, 3, 5, and 7, then the result is also a perfect number. Then save these numbers in the priority queue, and then pop up a current smallest number to multiply 2, 3, 5, 7 respectively. The popped numbers can be stored in the answer array (ensure that the answer data is in ascending order and not missed), and the new generation The number is added to the priority queue.
ac code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
set<ll> s; //判断之前是否出现过
vector<ll> v; //计入答案数组
priority_queue<ll, vector<ll>, greater<ll> >q; //最小堆,堆顶是最小元素
int a[] = {2, 3, 5, 7};
void init(){
q.push(1);
for(int i = 1; i <= 5842; i ++){ //一共询问5842
ll tmp = q.top(); q.pop();
v.push_back(tmp); //计入答案数组,下标从0开始
for(int j = 0; j < 4; j ++){
ll tt = tmp * a[j]; //分别乘2 3 5 7
if(s.count(tt)) continue; //之前存在过,跳过
s.insert(tt);
q.push(tt);
}
}
}
int main(){
init();
int n;
while(~scanf("%d", &n)){
printf("%d\n", v[n - 1]); //下标从0开始,所以要-1
}
return 0;
}