题目描述
见http://acm.hdu.edu.cn/showproblem.php?pid=2044
思路
一开始想用DFS求解,但递归深度太深,直接超时爆炸。不过可以用来验证一些简单情况(比如从1走到16)
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#define PI 3.1415927
#define INF 1000000000
using namespace std;
int n, m;
int a, b, c;
int v[2][51];
double ans, tmp;
int cnt = 0;
void dfs(int x, int y, int endx, int endy) {
if (x == endx && y == endy) {
cnt++;
return;
}
if (x > endx || y > endy) return;
if (x == 0) {
dfs(x, y + 1, endx, endy);
dfs(x + 1, y, endx, endy);
}
if (x == 1) {
dfs(x, y + 1, endx, endy);
dfs(x - 1, y + 1, endx, endy);
}
}
int findx(int t) {
if (t % 2 == 1) return 0;
else return 1;
}
int findy(int t) {
if (t % 2 == 1) return t / 2;
else return t / 2 - 1;
}
int main()
{
fill(v[0], v[0] + 2 * 51, -1);
scanf("%d", &n);
while (n--) {
cnt = 0;
scanf("%d%d", &a, &b);
dfs(findx(a), findy(a), findx(b), findy(b));
printf("%d\n", cnt);
}
return 0;
}
然后想到用递推求解,从终点思考,f(n) = f(n-1) + f(n-2),比如要走到12,只有从11或从10两种情况。这里要注意数据大小可能大于int范围(想了半天才想到到底哪出了问题!以后如果认为代码逻辑没错并且测试用例没错,出现wrong answer的情况,首先想想数据范围是否有问题),所以要定义double类型。
代码
#define ll long long
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#define PI 3.1415927
#define INF 1000000000
using namespace std;
int n, m;
int a, b, c;
double ans , tmp;
double v[51];
int main()
{
scanf("%d", &n);
while (n--) {
fill(v, v + 51, 0);
scanf("%d%d", &a, &b);
v[a] = 1;
for (int i = a + 1; i <= b; i++) {
v[i] = v[i - 1] + v[i - 2];
}
printf("%.0f\n", v[b]);
}
return 0;
}