Advertisement
Josif_tepe

Untitled

Mar 30th, 2025
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <map>
  5. using namespace std;
  6. typedef long long ll;
  7. const int maxn = 1e6 + 10;
  8.  
  9. int dist(int si, int sj, int ei, int ej) {
  10.     return abs(si - ei) + abs(sj - ej);
  11. }
  12. pair<int, int> idx[maxn];
  13. int main() {
  14.     ios_base::sync_with_stdio(false);
  15.     int r, c;
  16.     cin >> r >> c;
  17.    
  18.     vector<vector<int>> mat(r, vector<int>(c));
  19.     int cnt = 1;
  20.     for(int i = 0; i < r; i++) {
  21.         for(int j = 0; j < c; j++) {
  22.             cin >> mat[i][j];
  23.             idx[cnt] = {i, j};
  24.             cnt++;
  25.         }
  26.     }
  27.    
  28.     cnt = 1;
  29.     ll res = 0;
  30.     for(int i = 0; i < r; i++) {
  31.         for(int j = 0; j < c; j++) {
  32.             if(cnt != mat[i][j]) {
  33.                 pair<int, int> p = {i, j};
  34.                
  35.                 while(cnt != mat[p.first][p.second]) {
  36.                     res += dist(p.first, p.second, idx[mat[p.first][p.second]].first, idx[mat[p.first][p.second]].second);
  37.                     p = idx[mat[p.first][p.second]];
  38.                 }
  39.             }
  40.             cnt++;
  41.         }
  42.     }
  43.     cout << res << endl;
  44.    
  45.    
  46.    
  47.     return 0;
  48.    
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement