Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. #define pb push_back
  7.  
  8. using namespace std;
  9.  
  10. const int inf = 2e9 + 7;
  11. const int maxn = 110;
  12.  
  13. long long n, m, dp[maxn][maxn], a[maxn][maxn], mn = inf, x;
  14. vector <long long> v, cur;
  15.  
  16. bool check(int i, int j) {
  17. return (i >= 1 && i <= n && j >= 1 && j <= m);
  18. }
  19.  
  20. int main()
  21. {
  22. //freopen("input.txt", "r", stdin);
  23. //freopen("output.txt", "w", stdout);
  24. cin >> n >> m;
  25. for (int i = 1; i <= n; ++i) {
  26. for (int j = 1; j <= m; ++j) {
  27. cin >> a[i][j];
  28. dp[i][j] = inf;
  29. }
  30. }
  31. for (int i = 1; i <= n; ++i) {
  32. dp[i][1] = a[i][1];
  33. }
  34. for (int i = 1; i <= n; ++i) {
  35. for (int j = 1; j < m; ++j) {
  36. if (check(i + 1, j + 1)) {
  37. dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + a[i + 1][j + 1]);
  38. }
  39. if (check(i - 1, j + 1)) {
  40. dp[i - 1][j + 1] = min(dp[i - 1][j + 1], dp[i][j] + a[i - 1][j + 1]);
  41. }
  42. if (check(i, j + 1)) {
  43. dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + a[i][j + 1]);
  44. }
  45. }
  46. }
  47. for (int i = 1; i <= n; ++i) {
  48. if (dp[i][m] < mn) {
  49. mn = dp[i][m];
  50. x = i;
  51. }
  52. }
  53. for (int i = m; i >= 1; --i) {
  54. v.pb(x);
  55. if (dp[x - 1][i - 1] + a[x][i] == dp[x][i] && check(x - 1, i - 1)) {
  56. --x;
  57. }
  58. else if (dp[x][i - 1] + a[x][i] == dp[x][i] && check(x, i - 1)) {
  59. continue;
  60. }
  61. else if (dp[x][i - 1] + a[x][i] == dp[x][i] && check(x + 1, i - 1)) {
  62. ++x;
  63. }
  64. }
  65. reverse(v.begin(), v.end());
  66. for (int i = 0; i < v.size(); ++i) {
  67. cout << v[i] << " ";
  68. }
  69. cout << endl << mn;
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement