杭电oj HDOJ 1041 Computer Transformation(递推+大数处理)

杭电oj HDOJ 1041 Computer Transformation

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1041

Problem Description

A sequence consisting of one digit, the number 1 is initially written into a computer. At each successive time step, the computer simultaneously tranforms each digit 0 into the sequence 1 0 and each digit 1 into the sequence 0 1. So, after the first time step, the sequence 0 1 is obtained; after the second, the sequence 1 0 0 1, after the third, the sequence 0 1 1 0 1 0 0 1 and so on.

How many pairs of consequitive zeroes will appear in the sequence after n steps?

Input

Every input line contains one natural number n (0 < n ≤1000).

Output

For each input n print the number of consecutive zeroes pairs that will appear in the sequence after n steps.

题目大意

刚开始一个数列中只有一个数1,然后按照把1变成01、把0变成10的规则逐步地变换下去,现求当变换了n步后数列中“00”子列的数量。

解题思路

题中出现“00”时,一定是在“1001”中得到的,而n步中的“1001”是由n-1步中的“01”得到的,进一步,是由n-2步中的“1”得到的,列出前几项的变换结果可以得出“00”数量的递推公式,设res[n]为变换n步后数列中“00”的数量,则 r e s [ n ] = r e s [ n − 1 ] + 2 × r e s [ n − 2 ] res[n]=res[n-1]+2\times res[n-2] res[n]=res[n1]+2×res[n2]由于本题中数列的数字个数按指数级增长,所以数据量非常大,连__int64也无法表示完全,所以要用一个二位数组来进行递推的计算。

本人的C++解决方案

#include <iostream>
#include <stdio.h>
using namespace std;

int res[1000][400];

int main()
{
	int n, i, j, temp;
	res[0][0] = 0;
	res[1][0] = 1;
	for (i = 2; i < 1000; i++) {
		temp = 0;
		for (j = 0; j < 400; j++) {
			res[i][j] = res[i - 1][j] + 2 * res[i - 2][j] + temp;
			temp = res[i][j] / 10;
			res[i][j] %= 10;
		}
	}
	while (cin >> n) {
		if (n == 1) {
			printf("%d\n", 0);
		}
		else {
			// 确定开始位置
			for (i = 399; i >= 0; i--) {
				if (res[n - 1][i]) {
					break;
				}
			}
			// 倒叙输出
			for (; i >= 0; i--) {
				printf("%d", res[n - 1][i]);
			}
			printf("\n");
		}
	}
}

代码通过HDOJ平台运行通过,如发现错误,欢迎指出和纠正,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值