zoukankan      html  css  js  c++  java
  • 对动态规划的一点理解 Adjacent Bit Counts

    Adjacent Bit Counts

    时间限制:1000 ms | 内存限制:65535 KB

    难度:4

    • 描述

    • For a string of n bits x1, x2, x3, …, xn, the adjacent bit count of the string is given by fun(x) = x1*x2 + x2*x3 + x3*x 4 + … + xn-1*x n
      which counts the number of times a 1 bit is adjacent to another 1 bit. For example:

      Fun(011101101) = 3

      Fun(111101101) = 4

      Fun (010101010) = 0

      Write a program which takes as input integers n and p and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy Fun(x) = p.

      For example, for 5 bit strings, there are 6 ways of getting fun(x) = 2:

      11100, 01110, 00111, 10111, 11101, 11011

      • 输入

      • On the first line of the input is a single positive integer k, telling the number of test cases to follow. 1 ≤ k ≤ 10 Each case is a single line that contains a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by a decimal integer (p) giving the desired adjacent bit count. 1 ≤ n , p ≤ 100

      • 输出

      • For each test case, output a line with the number of n-bit strings with adjacent bit count equal to p.

      • 样例输入

      • 2
        5 2
        20 8 
        
      • 样例输出

      • 6
        63426
    我简单描述下题:
    用户输入正整数 n ,k
    X1,X2...只能为0或1
    输出满足
    X1*X2+X2*X3+....+X(n-1)*Xn=k;
    情况的个数
    
    穷举法的话肯定会超时。

    代码摘自: http://blog.csdn.net/air_one/article/details/11750509

     

    dp[达到的和][位置][0或1];

     

    1
    dp[101][101][2]

     

    初始化数组:

    for(j = 2; j < MAXN; j++)
    {
        dp[0][j][0] = dp[0][j-1][1] + dp[0][j-1][0];
        dp[0][j][1] = dp[0][j-1][0];
          
      
    }


     

    注意:dp[101][101][2]为全局变量,所以C语言自动把空白部分赋值为0;

    dp[0][j][0] = dp[0][j-1][1] + dp[0][j-1][0];     即总和为0,第j位为0的情况数=总和为0,第j-1位为1的情况数  + 总和为0,第j-1位为0的情况数

     dp[0][j][1] = dp[0][j-1][0]; 同理

     

    看计算过程:

    for(i = 1; i < MAXN; i++)
            for(j = 1; j < MAXN; j++)
            {
                dp[i][j][0] = dp[i][j-1][0] + dp[i][j-1][1];
                dp[i][j][1] = dp[i-1][j-1][1] + dp[i][j-1][0];
            }
            return 0;


     

    dp[i][j][0] = dp[i][j-1][0] + dp[i][j-1][1];    达到i,且j位为0的情况数= 达到i,第j-1位为0的情况数 + 达到i,第j-1位为1的情况数

     

    同理: dp[i][j][1] = dp[i-1][j-1][1] + dp[i][j-1][0];   达到i,且j位为1的情况数= 达到i-1,第j-1位为1的情况数 + 达到i,第j-1位为0的情况数

     

  • 相关阅读:
    基于Tire树和最大概率法的中文分词功能的Java实现
    通过 Spring RestTemplate 调用带请求体的 Delete 方法(Delete With Request Body)
    《高效能程序员的修炼》之译者序(本书将于7月初上市,人民邮电出版社)
    JVM类加载过程学习总结
    Web安全之Cookie劫持
    2016第40周五
    年轻By塞缪尔·厄尔曼
    2016第40周三
    2016第40周二
    果断歌
  • 原文地址:https://www.cnblogs.com/frankM/p/4399564.html
Copyright © 2011-2022 走看看