您的位置:首页 > 其它

Uva 10081 - Tight Words 解题报告(递推)

2014-03-31 16:35 501 查看

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
[i];
printf("%.5lf\n", ans*100);
}

int main()
{
int k, n;
while(~scanf("%d%d", &k, &n))
work(n, k);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息