回档|方格取数

题目描述 Description
设有N*N的方格图(N<=9),我们将其中的某些方格中填入正整数,而其他的方格中则放
人数字0。如下图所示(见样例):
A
0  0  0  0  0  0  0  0
0  0 13  0  0  6  0  0
0  0  0  0  7  0  0  0
0  0  0 14  0  0  0  0
0 21  0  0  0  4  0  0
0  0 15  0  0  0  0  0
0 14  0  0  0  0  0  0
0  0  0  0  0  0  0  0
                     B
    某人从图的左上角的A点出发,可以向下行走,也可以向右走,直到到达右下角的B
点。在走过的路上,他可以取走方格中的数(取走后的方格中将变为数字0)。
    此人从A点到B点共走两次,试找出2条这样的路径,使得取得的数之和为最大。

输入输出格式 Input/output
输入格式:
输入的第一行为一个整数N(表示N*N的方格图),接下来的每行有三个整数,前两个
表示位置,第三个数为该位置上所放的数。一行单独的0表示输入结束。
输出格式:
只需输出一个整数,表示2条路径上取得的最大的和。
 
输入样例:
8
2 3 13
2 6 6
3 5 7
4 4 14
5 2 21
5 6 4
6 3 15
7 2 14
0 0 0
输出样例: 67


题目解读:这道题目的关键就是两次路径的判定。那么不需要改变地图的坐标动归无疑是最好的选择。所以我们只需要搜索最优路径,再用动态规划把从剩余格子中找出最短路径。(膜拜MYF,这道题还可以用四维动归但实在不想写……)

var n,i,j,answer,t,k:longint; 
  a,map,p:array[0..11,0..11]of longint; 
function max(a,b:longint):longint; 
begin 
  if a>b then exit(a); 
  exit(b); 
end; 
procedure work(x,y,ans:longint); begin if (x<1)or(y<1)or(x>n)or(y>n) then exit; if (x=n)and(y=n) then begin p[n,n]:=0; ans:=ans+map[x,y]; for i:=1 to n do for j:=1 to n do a[i,j]:=map[i,j]*p[i,j]; for i:=1 to n do for j:=1 to n do a[i,j]:=a[i,j]+max(a[i-1,j],a[i,j-1]); answer:=max(answer,a[n,n]+ans); end; p[x,y]:=0; work(x,y+1,ans+map[x,y]); work(x+1,y,ans+map[x,y]); p[x,y]:=1; end;
begin readln(n); for i:=1 to n do for j:=1 to n do p[i,j]:=1; while true do begin readln(i,j,k); if i=0 then break; map[i,j]:=k; end; answer:=0; work(1,1,0); writeln(answer); end.

 

posted @ 2015-04-05 07:33  竹夭公子  阅读(169)  评论(0编辑  收藏  举报