题目来源:码蹄集
题目介绍:
B站老师思路讲解链接:https://www.bilibili.com/video/BV1r84y1E7TB/?t=1764.3&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118
C++代码实现:
原文参考链接:https://blog.51cto.com/u_15745546/5950626
#include <bits/stdc++.h>
using namespace std;
string a0 = "IAKIOI";
string a1 = "WHENWILLSCORLLOFTAIWUCOMEOUT!!!";
// 保存字符串数组
vector<string> ss = {a0, a1};
vector<unsigned long long> len_arr;
// 递推查找
char search(long long n, long long c) {
while (1) {
if (n == 0 || n == 1) {
return ss[n][c - 1];
}
long long len1 = len_arr[n - 2];
long long len2 = len_arr[n - 1];
if (c > len1) {
n = n - 1;
c = c - len1;
} else {
n = n - 2;
}
}
}
int main() {
int n = 0;
long long c = 0;
// 读取输入信息
cin >> n >> c;
// 初始化信息
len_arr.push_back(a0.length());
len_arr.push_back(a1.length());
// 获取第n项字符串的长度
for (int i = 2; i <= n; i++) {
len_arr.push_back(len_arr[len_arr.size() - 1] + len_arr[len_arr.size() - 2]);
}
printf("%c", search(n, c));
return 0;
}
Python代码实现:
a0 = "IAKIOI"
a1 = "WHENWILLSCORLLOFTAIWUCOMEOUT!!!"
# 保存字符串数组
ss = [a0, a1]
len_arr = [len(a0), len(a1)]
# 递推查找
def search(n, c):
while True:
if n == 0 or n == 1:
return ss[n][c - 1]
len1 = len_arr[n - 2]
len2 = len_arr[n - 1]
if c > len1:
n -= 1
c -= len1
else:
n -= 2
# 读取输入信息
n, c = map(int, input().split())
# 获取第n项字符串的长度
for i in range(2, n+1):
len_arr.append(len_arr[-1] + len_arr[-2])
print(search(n, c))
Java代码实现:
import java.util.*;
public class Main {
static String a0 = "IAKIOI";
static String a1 = "WHENWILLSCORLLOFTAIWUCOMEOUT!!!";
// 保存字符串数组
static ArrayList<String> ss = new ArrayList<>(Arrays.asList(a0, a1));
static ArrayList<Long> len_arr = new ArrayList<>();
// 递推查找
static char search(long n, long c) {
while (true) {
if (n == 0 || n == 1) {
return ss.get((int)n).charAt((int)c - 1);
}
long len1 = len_arr.get((int)n - 2);
long len2 = len_arr.get((int)n - 1);
if (c > len1) {
n = n - 1;
c = c - len1;
} else {
n = n - 2;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long c = sc.nextLong();
// 初始化信息
len_arr.add((long)a0.length());
len_arr.add((long)a1.length());
// 获取第n项字符串的长度
for (int i = 2; i <= n; i++) {
len_arr.add(len_arr.get(i - 2) + len_arr.get(i - 1));
}
System.out.printf("%c", search(n, c));
sc.close();
}
}