fork(19) download
  1. #include <stdio.h>
  2.  
  3. const int MAX = 50;
  4. const int MAX_D = 4;
  5. const int DOWN = 0, LEFT = 1, RIGHT = 2;
  6.  
  7. int G[MAX][MAX];
  8. int M[MAX][MAX][MAX * MAX][3];
  9. int n, m;
  10.  
  11. int max (int a, int b) { return a > b ? a : b; }
  12.  
  13. int f(int i, int j, int p, int d) {
  14. if (i == n || j == n || j < 0 || p == m)
  15. return 0;
  16. if (M[i][j][p][d] != -1)
  17. return M[i][j][p][d];
  18.  
  19. //We can always move down
  20. int ret = f(i + 1, j, p + 1, DOWN);
  21. //We have to check if we have enough steps to move sideways
  22. if((m-p) > (n-i)) {
  23. if(d == DOWN || d == RIGHT)
  24. ret = max(ret, f(i, j + 1, p + 1, RIGHT));
  25. if(d == DOWN || d == LEFT)
  26. ret = max(ret, f(i, j - 1, p + 1, LEFT));
  27. }
  28. return M[i][j][p][d] = ret + G[i][j];
  29. }
  30.  
  31. int main()
  32. {
  33. for (int i = 0; i < MAX; i++) {
  34. for (int j = 0; j < MAX; j++) {
  35. for (int p = 0; p < MAX * MAX; p++)
  36. for (int d = 0; d < MAX_D; d++)
  37. M[i][j][p][d] = -1;
  38. G[i][j] = 0;
  39. }
  40. }
  41.  
  42. scanf ("%d %d", &n, &m);
  43. for (int i = 0; i < n; i++)
  44. for (int j = 0; j < n; j++)
  45. scanf ("%d", &G[i][j]);
  46.  
  47. printf ("%d\n", f(0, 0, 0, DOWN));
  48. return 0;
  49. }
Success #stdin #stdout 0.08s 75968KB
stdin
3 5
1 1 30
1 1 1
1 1 1
stdout
34