zoukankan      html  css  js  c++  java
  • [CareerCup][Google Interview] 打印最长序列

    1. A
    2. Ctrl+A
    3. Ctrl+C
    4. Ctrl+V

    If you can only press the keyboard for N times (with the above four keys), please write a program to produce maximum numbers of A. If possible, please also print out the sequence of keys.

    So the input parameter is N (No. of keys that you can press), the output is M (No. of As that you can produce).

    这题又是一道经典的DP。打印这种类似最大结果的问题一般都会想到用DP

    f[i][4]: 表示有四种方法,f[i][j] = max(f[i-1][k] + 各种操作)

    如果要打印每个操作步骤,则要再设一个parent[i][j]数组,记录他的前任操作是哪个,然后递归调用。

     1 #include <iostream>
     2 using namespace std;
     3 
     4 int solve(int n)
     5 {
     6     int f[100][4];
     7 
     8     memset(f, 0, sizeof(f));
     9 
    10     f[0][0] = 1;
    11 
    12     for(int i = 1; i < n; i++)
    13         for(int j = 0; j < 4; j++)
    14             for(int k = 0; k < 4; k++)
    15             {
    16                 if (j == 0) // add A
    17                 {
    18                     f[i][j] = max(f[i][j], f[i-1][k] + 1);
    19                 }
    20                 else if (j == 1) // ctrl+A
    21                 {
    22                     f[i][j] = max(f[i][j], f[i-1][k]);
    23                 }
    24                 else if (j == 2) // ctrl+C
    25                 {
    26                     if (k == 1) // only previous is ctrl+A makes ctrl+C available
    27                         f[i][j] = max(f[i][j], f[i-1][k]);
    28                 }
    29                 else if (j == 3) //ctrl+V
    30                 {
    31                     if (k == 2)
    32                         f[i][j] = max(f[i][j], f[i-1][k] * 2);
    33                 }
    34             }
    35 
    36     return max(f[n-1][3], f[n-1][0]);
    37 }
    38 
    39 int main()
    40 {
    41     int N = 10;
    42     cout << solve(N) << endl;
    43 }
  • 相关阅读:
    随笔
    打破生活的套牢
    健忘是种美德
    【转贴】怎样冒充古典高手!
    php数组中删除元素
    JS 总结
    ubuntu apache rewrite
    JS 预览超级大图
    UBUNTU 安装SVN
    Yahoo14条前端优化规则
  • 原文地址:https://www.cnblogs.com/chkkch/p/2754297.html
Copyright © 2011-2022 走看看