ones
時間限制:1000 ms | 內存限制:65535 KB
難度:3
-
描述
- Given a positive integer N (0<=N<=10000), you are to find an expression equals to N using only 1,+,*,(,). 1 should not appear
continuously, i.e. 11+1 is not allowed.
-
輸入
- There are multiple test cases. Each case contains only one line containing a integer N
-
輸出
- For each case, output the minimal number of 1s you need to get N.
-
樣例輸入
-
2
10
-
樣例輸出
-
2
7
-
f(n - 1) + f(1);
-
f(n) = f (n / 2) + f(2);
-
f (n / 3) + f(3);
-
...
-
除數是100以內的素數
-
#include <iostream>
#include <cstdio>
#include <cstring>
#define N 10010
using namespace std;
int n;
int res[N];
bool visit[N];
int prime[110];
int len;
void init()
{
for (int i = 2; i * i < N; i++)
{
if (!visit[i])
{
prime[len++] = i;
for (int j = i + i; j < N; j += i)
visit[j] = 1;
}
}
}
int dp(int num)
{
if (res[num] != 0)
return res[num];
if (num == 1)
{
res[num] = 1;
return res[num];
}
int a = dp(num - 1) + 1;
for (int i = 0; prime[i] < num && i < len; i++)
{
if (num % prime[i] == 0)
{
int temp = dp(num / prime[i]) +dp(prime[i]);
if (a > temp)
a = temp;
}
}
res[num] = a;
return res[num];
}
int main()
{
init();
while (scanf("%d", &n) != EOF)
{
printf("%d\n", dp(n));
}
return 0;
}