素数的运用1

题目

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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值