先来份错误代码,亲爱的小伙伴们,希望你们能找到其中的问题,顺便说一句,用的是广搜
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
queue<long long> q;
int ans=1;
q.push(1);
while(ans!=1500)
{
long long x=q.front();
q.pop();
q.push(x*2); q.push(x*3); q.push(x*5);
ans++;
}
printf("%d\n",q.front());
return 0;
}
上面是我用很短的时间写出来的很漂亮的代码,如果说有什么不完美的地方,那就是他是错的。
有两点决定了他是错的,一,没有从小到大排序,这样实际上并不能确定谁是第1500个丑数,改进方法是用优先队列
二,同一个丑数可以有不同的生成方式,没有现判断该丑数是否已生成是第二个错误,改进方法是加入set判断
AC代码如下 time 0ms
#include<cstdio>
#include<queue>
#include<set>
#include<vector>
using namespace std;
typedef long long LL;
int d[]={2,3,5};
int main()
{
set<long long> s;
priority_queue<LL,vector<LL>,greater<LL> > q;
int ans=1;
s.insert(1);
q.push(1);
while(ans!=1500)
{
long long x=q.top();
q.pop();
for(int i=0;i<3;i++)
{
long long y=x*d[i];
if(!s.count(y)) { s.insert(y); q.push(y); }
}
ans++;
}
printf("The 1500'th ugly number is %lld.\n",q.top());
return 0;
}
再来份搞笑版的代码,可以AC 哦
#include<cstdio> using namespace std; int main() { printf("The 1500'th ugly number is 859963392.\n"); return 0; }