sudheerays123

Untitled

Jan 1st, 2020
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef unsigned long long int ll;
  4. #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
  5. #define INF 0x3f3f3f3f3f
  6.  
  7. ll dist(ll x1 , ll x2 , ll y1 , ll y2){
  8.  
  9.     ll x = (x1-x2)*(x1-x2);
  10.     ll y = (y1-y2)*(y1-y2);
  11.  
  12.     return ( x+y );
  13. }
  14.  
  15. int main() {
  16.  
  17.     fastio;
  18.  
  19.     ll n,m;
  20.     ll a[1005][2];
  21.     ll b[1005][2];
  22.     ll dp[1005][1005][2];
  23.  
  24.     cin >> n >> m;
  25.     for(ll i = 1; i <= n; i++) cin >> a[i][0] >> a[i][1];
  26.     for(ll i = 1; i <= m; i++) cin >> b[i][0] >> b[i][1];
  27.  
  28.     // OPTIMAL SUB-PROBLEM :
  29.  
  30.     // dp[i][j][0] = minimum energy needed with already first i h cows , first j g cows and going to the h cow
  31.     // dp[i][j][1] = minimum energy needed with already first i h cows , first j g cows and going to the g cow
  32.  
  33.     // BASE CASE :
  34.  
  35.     for(ll i = 0; i <= n; i++) {
  36.         for (ll j = 0; j <= m; j++) {
  37.             dp[i][j][0] = INF;
  38.             dp[i][j][1] = INF;
  39.         }
  40.     }
  41.  
  42.     dp[0][0][0] = 0;
  43.     dp[0][0][1] = 0;
  44.     dp[1][0][0] = 0;
  45.  
  46.    
  47.     // RECURSIVE RELATION :
  48.  
  49.    
  50.     for(ll i = 1; i <= n; i++){
  51.         for(ll j = 0; j <= m; j++){
  52.  
  53.             // dp[i][j][0] :
  54.             if(i > 1) dp[i][j][0] = min(dp[i][j][0] , dp[i-1][j][0] + dist(a[i-1][0] , a[i][0] , a[i-1][1] , a[i][1]));
  55.             if(i > 1 && j >= 1 ) dp[i][j][0] = min(dp[i][j][0] , dp[i-1][j][1] + dist(b[j-1][0] , a[i][0] , b[j-1][1] , a[i][1]));
  56.  
  57.             // dp[i][j][1] :
  58.  
  59.             if(j > 1 ) dp[i][j][1] = min(dp[i][j][1] , dp[i][j-1][0] + dist(a[j-1][0] , b[j][0] , a[j-1][1] , b[j][1]));
  60.             if(j > 1 ) dp[i][j][1] = min(dp[i][j][1] , dp[i][j-1][1] + dist(b[j-1][0] , b[j][0] , b[j-1][1] , b[j][1]));
  61.  
  62.         }
  63.     }
  64.  
  65.     // OPTIMAL SOLUTION :
  66.  
  67.  
  68.     cout << dp[n-1][m-1][0];
  69.  
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment