UVA 10081 - Tight Words (数论 dp)

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 differby more than 1.

Input is a sequence of lines, each line contains two integer numbersk and n, 1 <= n <= 100. For eachline of input, output the percentage of tight words of lengthn 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
题意:给定k,n。要求用0-k的数字组成长度为n的序列中,相邻两两差小于等于1的概率。

思路:dp,dp[i][j]表示组成长度为i,最后一个数字为j的符合条件的序列的概率。那么每次多一个数字的时候,只要加上dp[i][j - 1],dp[i][j + 1],dp[i][j],然后在除上多取一个数字的种数(k + 1)即可。

代码:

#include <stdio.h>
#include <string.h>

int k, n, i, j;
double dp[105][10];

int main() {
	while (~scanf("%d%d", &k, &n)) {
		memset(dp, 0, sizeof(dp));
		for (j = 0; j <= k; j ++)
			dp[1][j] = 1.0 / (k + 1);
		for (i = 2; i <= n; i ++) {
			for (j = 0; j <= k; j ++) {
				dp[i][j] += dp[i - 1][j];
				if (j) dp[i][j] += dp[i - 1][j - 1];
				if (j != k) dp[i][j] += dp[i - 1][j + 1];
				dp[i][j] /= (k + 1);
			}
		}
		double ans = 0;
		for (j = 0; j <= k; j ++)
			ans += dp[n][j];
		printf("%.5lf\n", ans * 100);
	}
	return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值