zcmu1178: 完美的数

题目链接:https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1178

题目大意

完美的数是他的质因子只有2,3,5,7,或者没有。问第n个完美数是多少?

思路

最小的完美数是1,然后针对每个完美数再分别乘2,3,5,7,那么结果也是完美数。那么将这些数存入优先队列,然后每次弹出一个当前最小的数分别去乘2,3,5,7,弹出的数可存入答案数组(保证答案数据升序且不遗漏),对新产生的数加入优先队列。

ac代码

#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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43911947/article/details/113099835