http://acm.hdu.edu.cn/showproblem.php?pid=1078
很好的一道题。因为它每次走到该格子的价值要比上一个格子大,所以在dp之前应该先对map[i][j]按价值排序,再开个标记数组标记某点是否可以到达。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int INF = 0x3f3f3f3f; int dp[110][110],map[110][110]; int vis[110][110]; struct node { int x,y; int data; bool operator < (const struct node &tmp)const { return data < tmp.data; } }point[10010]; int main() { int n,k; while(~scanf("%d %d",&n,&k)) { if(n == -1 && k == -1) break; int cnt = 0; for(int i = 1; i <= n; i++) { for(int j = 1;j <= n; j++) { scanf("%d",&map[i][j]); point[++cnt] = (struct node){i,j,map[i][j]}; } } sort(point+1,point+1+cnt); memset(vis,0,sizeof(vis)); memset(dp,0,sizeof(dp)); int x,y,ans,res; dp[1][1] = map[1][1]; res = dp[1][1]; for(int i = 1; i <= cnt; i++) { x = point[i].x; y = point[i].y; ans = -1; for(int j = 1; j <= k; j++) { if(x-j>=1 && map[x-j][y] < map[x][y] && !vis[x-j][y]) ans = max(dp[x-j][y],ans); if(x+j <= n && map[x+j][y] < map[x][y] && !vis[x+j][y]) ans = max(dp[x+j][y],ans); if(y-j >= 1 && map[x][y-j] < map[x][y] && !vis[x][y-j]) ans = max(dp[x][y-j],ans); if(y+j <= n && map[x][y+j] < map[x][y] && !vis[x][y+j]) ans = max(dp[x][y+j],ans); } if(ans == -1) { if(x == 1 && y == 1) continue; else { vis[x][y] = 1; dp[x][y] = 0; continue; } } dp[x][y] = map[x][y]+ans; res = max(res,dp[x][y]); } printf("%d\n",res); } return 0; }