4th IIUC Inter-University Programming Contest, 2005 |
|
I |
Walking on a Grid |
Input: standard input |
|
Problemsetter: Sohel Hafiz |
You will be given a square grid of size N × N. The top-left square has a coordinate of (1, 1) and that of bottom-right is (N, N). Your job is to walk from (1, 1) to (N, N). Very easy, right? That’s why you have to follow some rules when walking.
Input
Each case will start with two integers N and k. N ≤ 75 and k ≤ 5. Each of the next N lines will containN integers each given in row major order. That is, the first integer of the first row is (1, 1) and the last integer of last row is (N, N). Input terminates with two zeros on a line.
Output
For every case output the case number. If it’s not possible to reach the destination meeting the above rules then output “impossible”, else print the maximum sum of integers of the path.
Sample Input |
Output for Sample Input |
4 1 |
Case 1: 11 |
题意:给定n表示N x N的网格,k表示最多可以经过k个负数,然后输出该网格每一格的权值,要求出从(1,1) 走到 (N,N)经过路径的最大权值,只能往左右下3个方向。
思路:记忆化搜索,在普通dfs基础上,开一个四维数组,表示坐标和经过k个负数和进入方向。
代码:
#include <stdio.h> #include <string.h> const int MAXN = 80, INF = -200000000, d[3][2] = {{0, -1}, {0, 1}, {1, 0}}; int n, k, num[MAXN][MAXN], vis[MAXN][MAXN], i, j, kkk, l; long long dp[MAXN][MAXN][10][5], ans; void dfs(int x, int y, int kk, long long sum) { int i; if (kk > k) return; if (x == n - 1 && y == n - 1) { if (ans < sum) ans = sum; return; } for (i = 0; i < 3; i ++) { int xx = x + d[i][0]; int yy = y + d[i][1]; if (xx >= 0 && xx < n && yy >= 0 && yy < n && vis[xx][yy] == 0) { vis[xx][yy] = 1; if (num[xx][yy] < 0 && dp[xx][yy][kk + 1][i] < sum + num[xx][yy]) { dp[xx][yy][kk + 1][i] = sum + num[xx][yy]; dfs(xx, yy, kk + 1, sum + num[xx][yy]); } else if (num[xx][yy] >= 0 && dp[xx][yy][kk][i] < sum + num[xx][yy]) { dp[xx][yy][kk][i] = sum + num[xx][yy]; dfs(xx, yy, kk, sum + num[xx][yy]); } vis[xx][yy] = 0; } } } int main() { int t = 1; while (~scanf("%d%d", &n, &k) && n || k) { ans = INF; for (i = 0; i < n; i ++) for (j = 0; j < n; j ++) for (kkk = 0; kkk < 6; kkk ++) for (l = 0; l < 4; l ++) dp[i][j][kkk][l] = INF; memset(vis, 0, sizeof(vis)); vis[0][0] = 1; for (i = 0; i < n; i ++) for (j = 0; j < n; j ++) scanf("%d", &num[i][j]); if (num[0][0] < 0) { dfs(0, 0, 1, num[0][0]); } else { dfs(0, 0, 0, num[0][0]); } if (ans != INF) printf("Case %d: %lld\n", t ++, ans); else printf("Case %d: impossible\n", t ++); } return 0; }