UVA10081 POJ2537 ZOJ1883 Tight WordsDP

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10081 POJ2537 ZOJ1883 Tight WordsDP相关的知识,希望对你有一定的参考价值。

Tight words
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2845 Accepted: 1332

Description

Given is an alphabet {0, 1, … , k}, 0 <= k <= 9 . We say that a word of length n over this alphabet is tight if any two neighbour digits in the word do not differ by more than 1.

Input

Input is a sequence of lines, each line contains two integer numbers k and n, 1 <= n <= 100.

Output

For each line of input, output the percentage of tight words of length n over the alphabet {0, 1, … , k} with 5 fractional digits.

Sample Input

4 1
2 5
3 5
8 7

Sample Output

100.00000
40.74074
17.38281
0.10130

Source

Waterloo local 2001.01.27

问题链接UVA10081 POJ2537 ZOJ1883 Tight Words
问题简述:(略)
问题分析:动态规划问题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

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

/* UVA10081 POJ2537 ZOJ1883 Tight Words */

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 100;
double dp[N + 1][10];

int main()
{
    int k, n;
    while (scanf("%d%d", &k, &n) == 2) {
        memset(dp, 0, sizeof dp);
        for (int i = 0; i <= k; i++)
            dp[1][i] = 100.0 / (k + 1);
        for (int i = 1; i < n; i++)
            for (int j = 0; j <= k; j++)
                for (int l = -1; l <= 1; l++)
                    if (j + l >= 0 && j + l <= k)
                        dp[i + 1][j + l] += dp[i][j] / (k + 1);

        double ans = 0;
        for (int i = 0; i <= k; i++)
            ans += dp[n][i];

        printf("%.5f\\n", ans);
    }

    return 0;
}

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

/* UVA10081 POJ2537 ZOJ1883 Tight Words */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

const int N = 100;
double dp[N + 1][10];

int main()
{
    int k, n;
    while (scanf("%d%d", &k, &n) == 2) {
        memset(dp, 0, sizeof dp);
        double p = 1.0 / (k + 1);
        for (int i = 0; i <= k; i++)
            dp[1][i] = p;
        for (int i = 1; i < n; i++)
            for (int j1 = 0; j1 <= k; j1++)
                for (int j2 = 0; j2 <= k; j2++)
                    if (abs(j1 - j2) <= 1)
                        dp[i + 1][j2] += dp[i][j1] * p;

        double ans = 0;
        for (int i = 0; i <= k; i++)
            ans += dp[n][i];

        printf("%.5f\\n", ans * 100.0);
    }

    return 0;
}

以上是关于UVA10081 POJ2537 ZOJ1883 Tight WordsDP的主要内容,如果未能解决你的问题,请参考以下文章