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
解题报告: 直接求概率。在第一个数字的时候,0到k每个数字的概率都是1/k,都符合条件。第二个数字时,除了0和k,其他数字x可以由x-1,x,x+1转移,概率为1/k*(p(x)+p(x-1)+p(x+1)),0和k个少一个。按照此方式转移n-1次,最终求出概率和即可。复杂度为n*k,大约1000。如果n很大,达到100W级别那种,可以使用矩阵+二分快速幂,用矩阵表示每次转移时概率的变化。复杂度为k^3*log n,这题的话就别了。本人代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
double may[111][11];
void work(int n, int k)
{
if(k==0 || k==1)
{
puts("100.00000");
return;
}
for(int i=0;i<=k;i++)
may[1][i]=1.0/(k+1);
for(int i=2;i<=n;i++)
{
for(int j=1;j<k;j++)
may[i][j]=(may[i-1][j-1]+may[i-1][j]+may[i-1][j+1])/(k+1);
may[i][0]=(may[i-1][0]+may[i-1][1])/(k+1);
may[i][k]=(may[i-1][k]+may[i-1][k-1])/(k+1);
}
double ans=0;
for(int i=0;i<=k;i++)
ans+=may[n][i];
printf("%.5lf\n", ans*100);
}
int main()
{
int k, n;
while(~scanf("%d%d", &k, &n))
work(n, k);
}