1、hdu 1078 FatMouse and Cheese(搜索)
题意:小老鼠在n*n的矩阵里每个格子都藏了数目不定的奶酪,现在从(0,0)出发,每次最多走k格(每次只能从上下左右选一个方向走),每次只能走到奶酪数比当前格子奶酪数多的格子。求最多能获得多少奶酪。
思路:记忆化搜索。。DP?
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 const int maxn = 110; 5 const int INF = 0x7fffffff; 6 int mp[maxn][maxn]; 7 int dp[maxn][maxn]; 8 int n, k; 9 int dr[] = { 0,0,1,-1 }; 10 int dc[] = { 1,-1,0,0 }; 11 int DFS(int r,int c) 12 {//记忆化搜索DP 13 int ans = 0; 14 if (!dp[r][c]) 15 { 16 for (int i = 1; i <= k; i++) 17 { 18 for (int j = 0; j < 4; j++) 19 { 20 int tr = r + dr[j] * i; 21 int tc = c + dc[j] * i; 22 if (tr >= 0 && tr < n&&tc >= 0 && tc < n) 23 { 24 if (mp[tr][tc] > mp[r][c]) 25 { 26 ans = max(ans, DFS(tr,tc)); 27 } 28 } 29 } 30 } 31 dp[r][c] = ans + mp[r][c]; 32 } 33 return dp[r][c]; 34 } 35 struct node 36 { 37 int x; 38 int y; 39 node(int xx=0,int yy=0):x(xx),y(yy){ } 40 }; 41 int main() 42 { 43 while (~scanf("%d%d", &n, &k)) 44 { 45 if (n == -1 && k == -1)break; 46 for (int i = 0; i < n; i++) 47 { 48 for (int j = 0; j < n; j++) 49 { 50 scanf("%d", &mp[i][j]); 51 dp[i][j] = 0; 52 } 53 } 54 printf("%d ", DFS(0,0)); 55 } 56 return 0; 57 }
2、UVA 10047 The Monocycle
题意:从S走到T,每次只能向所朝方向前进一格或左转或右转,要求到T时车轮着地的颜色和初始位置相同,求最小时间。
思路:每个点维护方向和车轮着地颜色两个内容。
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 using namespace std; 6 const int maxl = 30; 7 char mp[maxl][maxl]; 8 bool vis[maxl][maxl][4][5]; 9 int m, n; 10 struct node 11 { 12 int x; 13 int y; 14 int d; 15 int s; 16 int c; 17 node(int xx=0,int yy=0,int dd=0,int ss=0,int cc=0):x(xx),y(yy),d(dd),s(ss),c(cc){ } 18 }; 19 int sx, sy, tx, ty; 20 //北、东、南、西 21 int dr[] = { -1,0,1,0 }; 22 int dc[] = { 0,1,0,-1 }; 23 int BFS() 24 { 25 queue<node>q; 26 q.push(node(sx, sy,0,0,0)); 27 vis[sx][sy][0][0] = true; 28 while (!q.empty()) 29 { 30 node u = q.front(); 31 q.pop(); 32 if (u.x == tx&&u.y == ty&&u.c==0) return u.s; 33 int d1 = (u.d + 1) % 4, d2 = (u.d - 1 + 4) % 4; 34 int dx = u.x + dr[u.d], dy = u.y + dc[u.d]; 35 if (dx< m&&dx>= 0 && dy< n&&dy >= 0) 36 { 37 if (!vis[dx][dy][u.d][(u.c+1)%5] && mp[dx][dy] != '#') 38 { 39 vis[dx][dy][u.d][(u.c + 1) % 5] = true; 40 q.push(node(dx, dy, u.d, u.s + 1,(u.c+1)%5)); 41 } 42 } 43 if (!vis[u.x][u.y][d1][u.c]) 44 { 45 vis[u.x][u.y][d1][u.c] = true; 46 q.push(node(u.x, u.y, d1, u.s + 1,u.c)); 47 } 48 if (!vis[u.x][u.y][d2][u.c]) 49 { 50 vis[u.x][u.y][d2][u.c] = true; 51 q.push(node(u.x, u.y, d2, u.s + 1,u.c)); 52 } 53 } 54 return -1; 55 } 56 57 int main() 58 { 59 int Case = 1; 60 while (~scanf("%d%d", &m, &n) && (m || n)) 61 { 62 for (int i = 0; i < m; i++) 63 { 64 scanf("%s", mp[i]); 65 for (int j = 0; j < n; j++) 66 { 67 if (mp[i][j] == 'S') sx = i, sy = j; 68 if (mp[i][j] == 'T') tx = i, ty = j; 69 } 70 } 71 memset(vis, 0, sizeof(vis)); 72 int ans = BFS(); 73 if (Case > 1) printf(" "); 74 if (ans == -1)printf("Case #%d destination not reachable ", Case++); 75 else printf("Case #%d minimum time = %d sec ", Case++, ans); 76 } 77 return 0; 78 }