LintCode-4 Keys Keyboard 数学解法

13 篇文章 0 订阅
867. 4 Keys Keyboard

Imagine you have a special keyboard with the following keys:

Key 1: (A): Print one ‘A’ on screen.

Key 2: (Ctrl-A): Select the whole screen.

Key 3: (Ctrl-C): Copy selection to buffer.

Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.

Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of ‘A’ you can print on screen.

注意事项
  1. 1 <= N <= 50
  2. Answers will be in the range of 32-bit signed integer.

样例

Given N = 3, return 3.

Explanation: 
We can at most get 3 A's on screen by pressing following key sequence:
A, A, A

Given N = 7, return 9.

Explanation: 
We can at most get 9 A's on screen by pressing following key sequence:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V

做的时候感觉应该有什么规律,没用dp做,憋了半天总算找出来了
结论是将N+1分解成整数个5和整数个4,不能满足的情况(N<=6,N=10)单列出来,有多少个4就乘多少个3,有多少个5就乘多少个4,两者乘积就是答案。

分析:
首先,N<=6时最大字符数即为N,A的输入次数<=5,且只会在一开始输入,一旦开始CV操作便不会再输入。
Ctrl+A,Ctrl+C,Ctrl+V一套下来会使之前的字符数*2,如果再加一个Ctrl+V就是*3(4次操作),再加一个是*4(5次操作),最多到*5(6次操作)。
因为五次Ctrl+V(7次操作)即n*6等同于n*2*3,没有意义。
因此,例如N=12可以拆分为4(输入3次A,3次操作)*3(CtrlA,CtrlC,CtrlV,CtrlV,4次操作)*3(同上,4次操作)
可以发现,复制时的操作次数-1=复制次数,而输入的操作次数=字符数;
但输入只进行一次,因此可以在一开始就将N+1,方便后面的计算。

另一方面,n*5在大部分情况下可以转化:
n*3*5(n*15)=n*4*4(n*16);(4+6=5+5操作次数),后者字符数更多
n*4*4*5(n*80)=n*3*3*3*3(n*81);(5+5+6=4+4+4+4),后者字符数更多
n*3*4*5=n*4*4*4,同第一种情况
……
可以看出,*5操作唯有在N=5和N=10(N+1==11,操作次数11=5+6=>4*5)时不能转化,必须使用,做一个判断即可。
综上,算法需要求尽可能多的*4,而前提是需要有足够更多的*3操作来保证操作次数正好用完,因此需要求一个整数线性规划:

min x/max y
S.T.
4x+5y=N(x为*3次数,y为*4次数)
x,y∈Z+
class Solution {
public:
    /**
     * @param N: an integer
     * @return: return an integer
     */
    int maxA(int N) {
        // write your code here
        if(N<=6) return N;
        N++;
        if(N-1==10) return 20;
        for(int n3=0;n3<=N/4;n3++)
        {
            if((N-n3*4)%5==0) return pow(3,n3)*pow(4,(N-n3*4)/5);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值