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

96 篇文章 0 订阅

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 n1 <= 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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值