ZOJ 1107FatMouse and Cheese(BFS)
分析: 一个n * n的图,每个点是一个奶酪的体积,从0,0开始每次最多可以走k步,下一步体积必须大于上一步,求最大体积和
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 const int Max = 550 + 10; 8 const int INF = 0x3f3f3f3f; 9 int g[Max][Max], dp[Max][Max]; 10 int n, k; 11 int gx[4] = {0, 0, 1, -1}; 12 int gy[4] = {1, -1, 0, 0}; 13 struct Node 14 { 15 int x, y; 16 17 }; 18 void bfs(int x, int y) 19 { 20 Node node; 21 node.x = x; 22 node.y = y; 23 dp[x][y] = g[x][y]; 24 queue<Node> que; 25 que.push(node); 26 int maxn = -INF; 27 while (!que.empty()) 28 { 29 node = que.front(); 30 que.pop(); 31 if (dp[node.x][node.y] > maxn) 32 maxn = dp[node.x][node.y]; 33 for (int i = 0; i < 4; i++) 34 { 35 for (int j = 1; j <= k; j++) 36 { 37 int fx = node.x + gx[i] * j; 38 int fy = node.y + gy[i] * j; 39 if (fx >= 1 && fy >= 1 && fx <= n && fy <= n && g[fx][fy] > g[node.x][node.y]) 40 { 41 if (dp[fx][fy] < g[fx][fy] + dp[node.x][node.y]) 42 { 43 dp[fx][fy] = g[fx][fy] + dp[node.x][node.y]; 44 Node temp; 45 temp.x = fx; 46 temp.y = fy; 47 que.push(temp); 48 } 49 } 50 } 51 } 52 } 53 printf("%d\n", maxn); 54 } 55 int main() 56 { 57 while (scanf("%d%d", &n, &k) != EOF) 58 { 59 if (n == -1 && k == -1) 60 break; 61 for (int i = 1; i <= n; i++) 62 for (int j = 1; j <= n; j++) 63 scanf("%d", &g[i][j]); 64 memset(dp, 0, sizeof(dp)); 65 bfs(1, 1); 66 } 67 return 0; 68 }