【洛谷】P1002 过河卒

P1002 [NOIP2002 普及组] 过河卒

过河卒

思路

dp/动态规划
1
2
3
4
5
6
7
A 0 0 0 0 0 0
0 0 X 0 X 0 0
0 X 0 0 0 X 0
0 0 0 M 0 0 0
0 X 0 0 0 X 0
0 0 X 0 X 0 0
0 0 0 0 0 0 B
1
2
3
4
5
6
7
1 1 1 1 1 1 1
1 0 X 1 X 1 2
1 X 0 1 1 X 2
1 1 1 M 1 1 3
1 X 1 1 0 X 3
1 1 X 1 X 0 3
1 2 2 3 3 3 6

map[i][j] = map[i - 1][j] + map[i][j - 1];

dfs
  1. 得分 60 Unaccepted
  2. #3 TLE #4 TLE
  3. P1002_3.in 20 20 4 0
  4. P1002_3.out 56477364570

代码

dp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstdio>
using namespace std;
int n, m, x, y;
long long map[42][42] = {{1}};
bool horse[42][42];
int hx[9] = {0, 1, 1, 2, 2, -1, -1, -2, -2},
hy[9] = {0, 2, -2, 1, -1, 2, -2, 1, -1};
int main()
{
cin >> n >> m >> x >> y;
for (int i = 0; i <= 8; i++)
{
int xx = x + hx[i], yy = y + hy[i];
if (xx > n || xx < 0 || yy > m || yy < 0)
continue;
horse[xx][yy] = 1;
}
int l = 0, k = 0;
while (!horse[0][++k] && k <= m)
map[0][k] = 1;
while (!horse[++l][0] && l <= n)
map[l][0] = 1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (!horse[i][j])
map[i][j] = map[i - 1][j] + map[i][j - 1];
cout << map[n][m] << endl;
return 0;
}
dfs+偏移量技巧 60分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<bits/stdc++.h>
using namespace std;

const int N=21;
int dx[]={2,1,-1,-2,-2,-1,1,2,}, dy[]={1,2,2,1,-1,-2,-2,-1};
int ddx[]={0,1},ddy[]={1,0};
int p[N][N];
int n,m;
int res=0;

void init()
{
for(int i=0;i<N;i++)
{
memset(p[i],0,sizeof(p[i]));
}
}
void horse(int x, int y)
{
p[x][y]=1;
for(int i=0;i<8;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a >= 0 && a <= n && b >= 0 && b <= m)
p[a][b]=1;
}
}
void dfs(int x,int y)
{
for(int i=0;i<2;i++)
{
int a=x+ddx[i],b=y+ddy[i];
if(a==n and b==m)
res++;
if(a >= 0 && a <= n && b >= 0 && b <= m &&p[a][b]!=1)
dfs(a,b);
}
}
int main()
{
int x,y;
cin>>n>>m>>x>>y;
init();
horse(x,y);
dfs(0,0);
cout<<res<<endl;
return 0;
}