題意:求第一個大於等於n的最小丑數
思路:就是簡單的單純模擬,然後二分求出來,看了下,按照題目範圍應該只有5195個醜數。有個注意的地方,判斷等於那裏不能寫成else if,因爲這樣會造成大量重複的醜數,直接爆掉
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5878
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
long long ans[100000];
int cnt;
long long Min(long long a, long long b, long long c, long long d)
{
long long temp1 = a < b ? a : b;
long long temp2 = c < d ? c : d;
return temp1 < temp2 ? temp1 : temp2;
}
void init()
{
cnt = 1;
int a1 = 0, a2 = 0, a3 = 0, a4 = 0;
ans[0] = 1;
while(true)
{
long long temp = Min(ans[a1] * 2, ans[a2] * 3, ans[a3] * 5, ans[a4] * 7);
ans[cnt++] = temp;
if(temp == ans[a1] * 2) a1++;
if(temp == ans[a2] * 3) a2++;//不能寫成else if
if(temp == ans[a3] * 5) a3++;
if(temp == ans[a4] * 7) a4++;
if(ans[cnt - 1] > 1000000000)
break;
}
}
int main()
{
init();
int t;
scanf("%d", &t);
while(t--)
{
long long n;
scanf("%I64d", &n);
int pos = lower_bound(ans, ans + cnt, n) - ans;
printf("%I64d\n", ans[pos]);
}
return 0;
}
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5878