题解:P15229 【LCOI R1 T1】Simple Sequence Evaluation
Eric20140331 · · 题解
P15229 题目解析 你需要解决的问题是根据给定的递推规则计算序列的第 n 项,其中 n 的范围可以达到 10 18
,因此暴力模拟递推会超时,必须找到序列的循环规律,用数学方法快速求解。 核心递推规则: A 0 =s 当 A i−1 ≥t 时, A i =A i−1 −a 当 A i−1 <t 时, A i =A i−1 +b 解题思路 循环检测:由于递推规则是固定的,序列最终会进入循环(因为每次操作都是加减固定值,状态有限)。 快速定位:记录每个状态首次出现的步数,当再次遇到该状态时,即可确定循环的起点和长度。 公式计算:利用循环的起点和长度,将大的 n 映射到循环内的位置,直接计算结果。 C++ 题解代码 cpp 运行
include <iostream>
include <unordered_map>
using namespace std;
typedef long long ll; const ll ppp = 1233321; // 题目要求的取模常量
ll solve(ll n, ll s, ll t, ll a, ll b) { unordered_map<ll, ll> pos; // 记录每个值出现的步数 ll current = s; pos[current] = 0; // 初始状态:步数0,值为s
for (ll step = 1; step <= n; ++step) {
// 计算下一步的值
if (current >= t) {
current -= a;
} else {
current += b;
}
// 检测是否出现循环
if (pos.count(current)) {
ll cycle_start = pos[current]; // 循环起点的步数
ll cycle_len = step - cycle_start; // 循环长度
ll remain = n - cycle_start; // 循环起点到n的步数
remain %= cycle_len; // 映射到循环内的位置
n = cycle_start + remain; // 新的n,大幅减小计算量
pos.clear(); // 清空哈希表,重新计算
current = s;
pos[current] = 0;
step = 0; // 重置步数,重新循环
continue;
}
pos[current] = step;
}
return current % ppp; // 最终结果对ppp取模
}
int main() { ios::sync_with_stdio(false); cin.tie(0); // 加速输入输出
int T;
cin >> T;
while (T--) {
ll n, s, t, a, b;
cin >> n >> s >> t >> a >> b;
cout << solve(n, s, t, a, b) << '\n';
}
return 0;
} 代码关键部分解释 哈希表 pos: 键:序列中的值 current 值:该值首次出现的步数 step 作用:检测循环,当某个值再次出现时,说明进入循环。 循环处理逻辑: 当检测到循环时,计算循环起点 cycle_start 和循环长度 cycle_len。 将大的 n(如 10 18
)转换为 cycle_start + (n - cycle_start) % cycle_len,大幅减少需要递推的步数。 输入输出优化: ios::sync_with_stdio(false); 和 cin.tie(0); 关闭 cin 与 stdio 的同步,加速输入输出(应对 T=1e4 的大数据)。 取模处理: 最终结果对 ppp=1233321 取模,符合题目要求。 样例验证 以第一组样例 2 1 2 3 4 为例: step0: current=1(<2)→ step1: 1+4=5 step1: current=5(≥2)→ step2:5-3=2 最终结果为 2,与样例输出一致。 第二组样例 3 0 10 5 5: step0: 0(<10)→ step1:0+5=5 step1:5(<10)→ step2:5+5=10 step2:10(≥10)→ step3:10-5=5 最终结果为 5,与样例输出一致。 总结 核心思想:暴力递推超时,需通过哈希表检测循环,将大 n 映射到循环内的小步数计算。 关键优化:利用循环规律,将时间复杂度从 O (n) 降至 O (循环长度),可处理 10 18
级别的 n。 实现细节:输入输出加速、哈希表记录状态、循环映射公式是解题的关键。