题目
Initially on a notepad only one character ‘A’ is present. You can perform two operations on this notepad for each step:
Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n ‘A’ on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n ‘A’.
Example 1:
Input: 3
Output: 3
Explanation:
Intitally, we have one character ‘A’.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get ‘AA’.
In step 3, we use Paste operation to get ‘AAA’.
分析
一个素数由于没有任何的因数,因此只能一直粘贴A得到。而对于一个合数来说,其可以通过分解成两个因数数如a和b,通过a次粘贴b个A可以得到n个A(n = a * b)。因此可以得到迭代式 d[n] = d[a] * b ,根据经验可以知道当粘贴次数b比较小的时候,能够快速的得到n个A,这里就不具体严格证明了。并且a、b分布在sqrt(n)的两边,因此可以确定b的范围是[1:sqrt(n)],通过循环找到其中正确的合数,因此可以得到很多的这样的因数分解,对其进行比较,d[n] = min(d[a] * b) 。由于其中含有很多重叠的子问题,因此可以使用动态规划的思想降低复杂度。以下的代码使用了记忆化搜素,本质和动态规划是一致的。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int * newIntRaw(int n)
{
return (int *)malloc(sizeof(int) * n);
}
int * newInt(int n, int init)
{
int *p = newIntRaw(n);
int i;
for (i = 0; i < n; ++i)
p[i] = init;
return p;
}
int min(int a, int b)
{
return a < b ? a : b;
}
int *memo;
int calcMinSteps(int n)
{
int i;
int res;
if (memo[n] != -1)
return memo[n];
if (n == 2)
return memo[n] = 2;
else if (n == 3)
return memo[n] = 3;
res = n;
for (i = sqrt(n); i > 1; --i) {
if (n % i == 0) {
res = min(res, calcMinSteps(n/i) + i);
}
}
return memo[n] = res;
}
int minSteps(int n)
{
int res;
if (n <= 1)
return 0;
memo = newInt(n + 1, -1);
res = calcMinSteps(n);
free(memo);
return res;
}
int main()
{
int n;
scanf("%d", &n);
printf("%d\n", minSteps(n));
return 0;
}
/*
13
output: 13
21
output: 10
10
output: 7
*/