Sicily 11599. Tight words





11599. Tight words
 
     
     
 
Time Limit: 1sec    Memory Limit:256MB
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. Your task is to find out the percentage of tight words of length n over the given alphabet.

Input

Input is a sequence of lines, each line contains two integer numbers k and n1 <= 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
 Copy sample input to clipboard
4 1
2 5
3 5
8 7
Sample Output
100.00000
40.74074
17.38281
0.10130

題意是用0到k這k+1個符號,組成一個n位的數,如果這個n位數相鄰的位置上的數字差都不超過1,那麼這個n位數就稱爲tight words,最後問tight words的個數佔總數的百分比,因爲總數有(k+1)^n之多,所以只能用double來存儲了,我們用dp[i][j]表示i位數,最高位上是j的tight words的個數,初始化後,很容易就可以遞推出來,因爲個數比較大,long long也存不下,只能使用double了。

這道題目簡單的數位dp,狀態轉移很簡單,處理好邊界就可以了。

// Problem#: 11599
// Submission#: 3667449
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cmath>
#include <ctime>
#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
double dp[111][111];
int main(int argc, char *argv[]){
    int k, n;
    int N=111; 
    while (scanf("%d%d",&k,&n)!=EOF){
        for (int i = 0; i < N; ++i){
            for (int j = 0; j < N; ++j){
                dp[i][j] = 1.0;
            }
        }
        for (int i = 2; i<N; ++i){
            for (int j = 0; j<= k;++j){
                dp[i][j] = dp[i-1][j];
                if (j > 0){
                    dp[i][j] += dp[i-1][j-1];
                }
                if (j < k) {
                    dp[i][j] += dp[i-1][j+1];
                }
            }
        }
        double ans = 0;
        double base = pow(k + 1, n);
        for (int i = 0; i <= k; ++i) {
            ans += dp[n][i];
        }
        printf("%.5f\n", ans * 100.0 / base);
    }
    return 0;
}                                 



發佈了20 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章