Advertisement
Josif_tepe

Untitled

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