洛谷P1096 Hanoi 双塔问题 题解 递归

题目链接:https://www.luogu.com.cn/problem/P1096

解题思路:

递归。

推导公式:
\(f[1] = 2\)
\(f[i] = f[i-2] \cdot 2 + 2\)

因为数据比较大,需要用到高精度。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 220;
int a[maxn+1], n;
int main() {
    cin >> n;
    a[0] = 2;
    for (int i = 1; i < n; i ++) {
        for (int j = 0; j < maxn; j ++) a[j] *= 2;
        a[0] += 2;
        for (int j = 0; j < maxn; j ++) {
            a[j+1] += a[j] / 10;
            a[j] %= 10;
        }
    }
    int i = maxn-1;
    while (!a[i]) i --;
    while (i >= 0) cout << a[i--];
    cout << endl;
    return 0;
}
posted @ 2020-02-07 12:14  quanjun  阅读(271)  评论(0)    收藏  举报