街道问题扩展.pas 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const
  2. maxn=90;
  3. type
  4. tt=array[1..maxn,1..maxn]of longint;
  5. var
  6. row,col:byte;
  7. best,b:tt;
  8. map:array[0..1]of tt;
  9. k,m:longint;
  10. procedure init;
  11. var
  12. i,j:longint;
  13. begin
  14. readln(row,col);
  15. for i:=1 to row do
  16. begin
  17. for j:=1 to col-1 do
  18. read(map[0,i,j]);
  19. readln
  20. end;
  21. for j:=1 to col do
  22. begin
  23. for i:=1 to row-1 do
  24. read(map[1,i,j]);
  25. readln;
  26. end;
  27. end;
  28. function getET(s,u:longint;var e:longint;var t:longint):boolean;
  29. begin
  30. if ((k>=row)and(s=1)and(u=1))or
  31. (k>=col)and(s=m)and(u=0)
  32. then begin
  33. getET:=false;
  34. exit;
  35. end;
  36. if k<row
  37. then begin
  38. e:=map[u,k+1-s,s];
  39. t:=s+1-u;
  40. end
  41. else begin
  42. e:=map[u,row+1-s,k-row+1];
  43. t:=s-u;
  44. end;
  45. getET:=true;
  46. end;
  47. procedure main;
  48. var
  49. s1,s2,
  50. u1,u2,
  51. t1,t2,
  52. m1,m2,
  53. e1,e2:longint;
  54. begin
  55. if row<col
  56. then begin
  57. m1:=row;
  58. m2:=col;
  59. end
  60. else begin
  61. m1:=col;
  62. m2:=row;
  63. end;
  64. best[1,1]:=0;
  65. for k:=row+col-2 downto 1 do
  66. begin
  67. if k<m1
  68. then m:=k
  69. else if k>m2
  70. then m:=row+col-k
  71. else m:=m1;
  72. b:=best;
  73. for s1:=1 to m do
  74. for s2:=1 to m do
  75. begin
  76. best[s1,s2]:=maxlongint;
  77. for u1:=0 to 1 do
  78. if getET(s1,u1,e1,t1)
  79. then for u2:=0to 1 do
  80. begin
  81. if ((s1<>s2)or(u1<>u2))and (b[t1,t2]+e1+e2<best[s1,s2])
  82. then if getET(s2,u2,e2,t2)
  83. then best[s1,s2]:=b[t1,t2]+e1+e2;
  84. end;
  85. end;
  86. end;
  87. end;
  88. begin
  89. init;
  90. main;
  91. writeln(best[1,1]);
  92. end.