骗分技巧
liyuanchen2021 · · 个人记录
在信息学竞赛中,难免会遇到不会做的题,我们有时可以用骗分的方式来解决。
骗分方法
-
对于小数据,可进行暴力模拟。
-
对于较大数据,可使用枚举和搜索算法。
-
打表是一种以空间换时间的好方法,有时还可以避免TLE(解释见下方)。
什么是打表?
打表是一种以空间换时间的方法,以 斐波那契数列 为例。
递归算法代码:
#include <iostream>
using namespace std;
int f(int x) {
if (x <= 2) return 1;
else return f(x - 1) + f(x - 2);
}
int main() {
int n, a;
cin >> n;
while (n--) {
cin >> a;
cout << f(a) << endl;
}
return 0;
}
提交后运行时长约为 18ms。
打表优化代码:
#include <iostream>
using namespace std;
int memory[40];
int f(int x) {
if (memory[x] != 0) return memory[x];
else if (x <= 2) return memory[x] = 1;
else return memory[x] = f(x - 1) + f(x - 2);
}
int main() {
int n, a;
cin >> n;
while (n--) {
cin >> a;
cout << f(a) << endl;
}
return 0;
}
提交后运行时长约为 11ms,比优化前的用时快了一点。
由此可见,打表确实是一种提高效率的好方法。