Advertisement
Josif_tepe

Untitled

Mar 29th, 2025
484
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 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. pair<int, int> idx[maxn];
  10. int dist(int i, int j, int ci, int cj) {
  11.     return abs(j - cj) + abs(i - ci);
  12. }
  13. map<int, int> mapa;
  14. vector<pair<int, int>> graph[maxn];
  15. int main() {
  16.     ios_base::sync_with_stdio(false);
  17.     int r, c;
  18.     cin >> r >> c;
  19.    
  20.     vector<vector<int>> mat(r, vector<int>(c));
  21.     int cnt = 1;
  22.     for(int i = 0; i < r; i++) {
  23.         for(int j = 0; j < c; j++) {
  24.             cin >> mat[i][j];
  25.            
  26.             idx[cnt] = make_pair(i, j);
  27.             cnt++;
  28.         }
  29.     }
  30.     int n = r * c;
  31.    
  32.     for(int i = 0; i < r; i++) {
  33.         for(int j = 0; j < c; j++) {
  34.             graph[mat[i][j]].push_back(make_pair(mat[idx[mat[i][j]].first][idx[mat[i][j]].second], dist(i, j, idx[mat[i][j]].first, idx[mat[i][j]].second)));
  35.         }
  36.     }
  37.    
  38.     vector<bool> visited(n + 1);
  39.     for(int i = 1; i <= n; i++) {
  40.         if(!visited[i]) {
  41.            
  42.             visited[i] = true;
  43.             queue<int> q;
  44.             q.push(i);
  45.             cout << i << " ";
  46.             ll sum = 0;
  47.             while(!q.empty()) {
  48.                 int c = q.front();
  49.                 q.pop();
  50.                
  51.                
  52.                 for(int i = 0; i < (int) graph[c].size(); i++) {
  53.                     int neighbour = graph[c][i].first;
  54.                     int weight = graph[c][i].second;
  55.                    
  56.                     if(!visited[neighbour]) {
  57.                         cout << weight << " " << neighbour << " ";
  58.                         visited[neighbour] = true;
  59.                         q.push(neighbour);
  60.                        
  61.                         sum += weight;
  62.                         mapa[neighbour] = sum;
  63.                     }
  64.                    
  65.                    
  66.                 }
  67.             }
  68.             cout << endl;
  69.         }
  70.     }
  71.    
  72.     for(pair<int, int> m : mapa) {
  73.         cout << m.first << " " << m.second << endl;
  74.     }
  75.    
  76.    
  77.     return 0;
  78.    
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement