问题 C: 完美的数
时间限制: 1 Sec 内存限制: 128 MB
[提交][状态][讨论版]
题目描述
一个数是否完美是这样定义的,如果这个数的素数因子只有2,3,5,7,那么这个数就是完美的.
显而易见前面几个完美的数为1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, …
你能告诉我第n个完美的数是多少嘛?
输入
多组测试数据.每组数据的第一行包含一个正整数n(1<= n<=5842).
输出
对于每组测试数据输出第n个完美的数
样例输入
1
11
5842
样例输出
1
12
2000000000
提示
/*
打表。
用优先队列。
首先1入队,
然后1出队,出队的同时记录结果,分别乘2,3,5,7,得到的结果入队列
然后再让队列中一个元素出队(最大的最小的都可以,我是让最小的出队),出队的同时记录结果,分别乘2,3,5,7,得到的<=2e9的结果入队列
直到队列为空。
*/
ac_code:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL maxn = 6000;
const LL up = 2e9;
LL mp[maxn];
LL step[]= {2,3,5,7};
priority_queue<LL>q;
map<LL,bool>vis;
int main()
{
int cnt = 0;
vis[1] = true;
q.push(-1);
while(!q.empty())
{
LL k = -q.top();
mp[++cnt] = k;
q.pop();
for(int i = 0; i < 4; i++)
{
LL temp = k*step[i];
if(temp <= up && !vis[temp])
{
vis[temp] = true;
q.push(-temp);
}
}
}
LL n;
while(~scanf("%lld",&n))
{
printf("%lld\n",mp[n]);
}
return 0;
}
一个学长的巧妙的解法:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 6e3;
int mp[maxn];
int main()
{
int i = 0;
int x,y,l,r;
mp[++i] = 1;
x = y = l = r = 1;
while(i <= 5842)
{
int t = min(mp[x]*2,min(mp[y]*3,min(mp[l]*5,mp[r]*7)));
if(t == mp[x]*2) x++;
if(t == mp[y]*3) y++;
if(t == mp[l]*5) l++;
if(t == mp[r]*7) r++;
mp[++i] = t;
}
int n;
while(~scanf("%d",&n))
{
printf("%d\n",mp[n]);
}
return 0;
}