Problem B : Tight Words
Problem B: Tight words
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 is a sequence of lines, each line contains two integer numbers k and n, 1 <= n <= 100. 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
Output for the sample input
100.00000 40.74074 17.38281 0.10130
#include <iostream> #include <cstdio> #include <cmath> using namespace std; const int maxn = 110; double dp[20][20][maxn]; void initial(){ for(int i = 0;i < 20;i++){ for(int j = 0;j < 20;j++){ dp[i][j][1] = 1.0/(1.0*(1+i)); } } for(int m = 1;m < 10;m++){ for(int k = 2;k <= 100;k++){ for(int i = 0;i <= m;i++){ dp[m][i][k] = dp[m][i][k-1]; if(i-1 >= 0 && i-1 <= m){ dp[m][i][k] += dp[m][(i-1+m)%m][k-1]; } if(i+1 >= 0 && i+1 <= m){ dp[m][i][k] += dp[m][i+1][k-1]; } dp[m][i][k] /= (1.0*(1+m)); } } } } int main(){ initial(); int k , n; while(cin >> k >> n){ if(k == 0 || k == 1 || n == 1){ printf("100.00000\n"); }else{ double sum = 0.0; for(int i = 0;i <= k;i++){ sum += dp[k][i][n]; } printf("%.5lf\n" , sum*100.0); } } return 0; }