【递推】【巧妙模拟】【思维】ZOJ 1633 Big String 【拼接两个字符串】
We will construct an infinitely long string from two short strings: A = “^__^” (four characters), and B = “T.T” (three characters). Repeat the following steps:
- Concatenate A after B to obtain a new string C. For example, if A = “^__^” and B = “T.T”, then C = BA = “T.T^__^”.
- Let A = B, B = C – as the example above A = “T.T”, B = “T.T^__^”.
Your task is to find out the n-th character of this infinite string.
Input
The input contains multiple test cases, each contains only one integer N (1 <= N <= 2^63 - 1). Proceed to the end of file.
Output
For each test case, print one character on each line, which is the N-th (index begins with 1) character of this infinite string.
Sample Input
1
2
4
8
Sample Output
T
.
^
T
题意:
A = "^__^"
B = "T.T"
不断执行
C = BA
B = C
A = B
将AB串拼接起来,构成一个无限长的字符串T.T^__^T.TT.T^__^......
问第n个字符是什么
思路:
因为这个字符串是由两个基本串构成的,因此只需要用基本串的长度3 ,4来模拟拼接过程,然后判断第n个字符在基本串的哪里即可。
f[i]
表示第i次拼接后字符串的长度- 模拟拼接过程 即递归过程
f[i] = f[i - 1] + f[i - 2]
- 判断第n个字符在基本串的哪里:找到第一个小于n的字符串长度(使用low_bound),这个字符串就是拼接在第n位前面的子串,逆拼接过程逆拼接过程,将这个子串去掉(也就是
n -= f[i]
),一直重复该过程,直到n < 7
,即可以在标准串T.T^__^
中找到他的位置。
AC代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn = 100;
long long f[maxn];
int main()
{
string c = "T.T^__^";
f[0] = 4;
f[1] = 3;
for(int i = 2; i < 90; i++)
f[i] = f[i - 1] + f[i - 2];
long long n;
while(~scanf("%lld", &n))
{
while(n > 7)
{
int p = lower_bound(f, f + 90, n) - f;
n -= f[p - 1];
}
printf("%c\n", c[n - 1]);
}
return 0;
}