Advertisement
KennasSticky

p82_DP

Feb 8th, 2022
1,532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <chrono>
  5.  
  6. using namespace std;
  7. using namespace std::chrono;
  8.  
  9. int main()
  10. {
  11.  
  12.   ios_base::sync_with_stdio(false);
  13.   cin.tie(NULL);
  14.  
  15.   // STANDARD INPUT
  16.  
  17.   auto start = high_resolution_clock::now();
  18.  
  19.   FILE *txtfile = fopen("p082_matrix.txt", "r");
  20.  
  21.   int arr[80][80];
  22.  
  23.   for (int i = 0; i < 80; i++)
  24.   {
  25.     for (int j = 0; j < 80; j++)
  26.     {
  27.       fscanf(txtfile, "%d", &arr[i][j]);
  28.       fgetc(txtfile);
  29.     }
  30.   }
  31.  
  32.   fclose(txtfile);
  33.  
  34.   // ANSWER
  35.  
  36.   // Get starting timepoint
  37.  
  38.   int dp[80];
  39.  
  40.   // INIT DP
  41.   for (int i = 0; i < 80; i++)
  42.   {
  43.     dp[i] = arr[i][79];
  44.   }
  45.  
  46.   for (int i = 78; i >= 0; i--)
  47.   {
  48.     dp[0] += arr[0][i]; // CREATE HORZ SUM FOR FIRST ROW BECAUSE THE FIRST ROW CANNOT MOVE UP
  49.  
  50.     for (int j = 1; j < 80; j++)
  51.     {
  52.       dp[j] = min(dp[j - 1] + arr[j][i], dp[j] + arr[j][i]);
  53.  
  54.       // PAR 1 = UPWARD MOVEMENT
  55.       // PAR 2 = RIGHTWARD MOVEMENT
  56.     }
  57.  
  58.     for (int j = 78; j >= 0; j--)
  59.     {
  60.       dp[j] = min(dp[j], dp[j + 1] + arr[j][i]); // CHECK IF DOWNWARD MOTION IS CHEAPER
  61.     }
  62.   }
  63.  
  64.   int ans = INT_MAX;
  65.  
  66.   for (int i = 0; i < 80; i++)
  67.   {
  68.     ans = min(ans, dp[i]); // THE ANS AT ROW I REPRESENTS THE MINIMUM PATH FROM THE LEFT TO RIGHT HAND SIDE STARTING AT ROW [I,0]
  69.   }
  70.  
  71.   cout << ans << "\n";
  72.  
  73.   // Get ending timepoint
  74.   auto stop = high_resolution_clock::now();
  75.  
  76.   // Get duration. Substart timepoints to
  77.   // get durarion. To cast it to proper unit
  78.   // use duration cast method
  79.   auto duration = duration_cast<microseconds>(stop - start);
  80.  
  81.   cout << "Time taken by function: "
  82.        << duration.count() << " microseconds" << endl;
  83.  
  84.   return 0;
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement