UVA10721 Bar Codes【動態規劃DP】

A bar-code symbol consists of alternating dark and light bars, starting with a dark bar on the left. Each bar is a number of units wide. Figure 1 shows a bar-code symbol consisting of 4 bars that extend over 1 + 2 + 3 + 1 = 7 units.

在這裏插入圖片描述
Figure 1: Bar-code over 7 unitswith 4 bars

In general, the bar code BC(n, k, m) is the set of all symbols with k bars that together extend over exactly n units, each bar being at most m units wide. For instance, the symbol in Figure 1 belongs to BC(7,4,3) but not to BC(7,4,2). Figure 2 shows all 16 symbols in BC(7,4,3). Each ‘1’ represents a dark unit, each ‘0’ a light unit.

0: 1000100 | 4: 1001110 | 8: 1100100 | 12: 1101110
1: 1000110 | 5: 1011000 | 9: 1100110 | 13: 1110010
2: 1001000 | 6: 1011100 | 10: 1101000 | 14: 1110100
3: 1001100 | 7: 1100010 | 11: 1101100 | 15: 1110110
Figure 2: All symbols of BC(7,4,3)
Input
Each input will contain three positive integers n, k, and m (1 ≤ n, k, m ≤ 50).
Output
For each input print the total number of symbols in BC(n, k, m). Output will fit in 64-bit signed integer.
Sample Input
7 4 3
7 4 2
Sample Output
16
4

問題鏈接UVA10721 Bar Codes
問題簡述:給定正整數n,k和m,用k個1~m的數組成n,問有幾種組成方法。
問題分析
    一種方法是構建狀態轉換方程:dp[i][j]表示用i個數組成j, dp[i][j] = ∑(1 ≤ t ≤min(k, j)) dp[i - 1][t]。
    另外一種方法是定義f(i, j, k)爲i分成j部分,每個部分不超過k的組成方法,則狀態轉換方程爲f(i, j, k)=sum(dp(i - p, j - 1, k)),其中1 ≤ p ≤ k。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的C++語言程序如下:

/* UVA10721 Bar Codes */

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
const int N = 50;
LL dp[N + 1][N + 1];

int main()
{
    int n, k, m;
    while(~scanf("%d%d%d", &n, &k, &m)) {
        memset(dp, 0, sizeof(dp));
        dp[0][0] = 1;
        for(int i = 1; i <= k; i++)
            for(int j = 1; j <=n; j++)
                for(int k = 1; k <= m && k <= j; k++)
                    dp[i][j] += dp[i - 1][j - k];

        printf("%lld\n", dp[k][n]);
    }

    return 0;
}

AC的C++語言程序如下:

/* UVA10721 Bar Codes */

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
const int N = 50;
LL dp[N + 1][N + 1][N + 1];

// dp(i. j, k) = sum( dp(i - p, j - 1,  k) ) 1 ≤ p ≤ k
void dpInit()
{
    memset(dp, 0, sizeof(dp));

    for (int i = 0; i <= N; i++)
        dp[0][0][i] = 1LL;
    for (int i = 1; i <= N; i++)
        for (int j = 1; j <= N; j++)
            for (int k = 1; k <= N; k++)
                for (int p = 1; p <= k && p <= i; p++)
                    dp[i][j][k] += dp[i - p][j - 1][k];
}

int main()
{
    dpInit();

    int n, k, m;
    while(~scanf("%d%d%d", &n, &k, &m))
        printf("%lld\n", dp[n][k][m]);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章