Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <map>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e6 + 10;
- pair<int, int> idx[maxn];
- int dist(int i, int j, int ci, int cj) {
- return abs(j - cj) + abs(i - ci);
- }
- map<int, int> mapa;
- vector<pair<int, int>> graph[maxn];
- int main() {
- ios_base::sync_with_stdio(false);
- int r, c;
- cin >> r >> c;
- vector<vector<int>> mat(r, vector<int>(c));
- int cnt = 1;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- cin >> mat[i][j];
- idx[cnt] = make_pair(i, j);
- cnt++;
- }
- }
- int n = r * c;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- 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)));
- }
- }
- vector<bool> visited(n + 1);
- for(int i = 1; i <= n; i++) {
- if(!visited[i]) {
- visited[i] = true;
- queue<int> q;
- q.push(i);
- cout << i << " ";
- ll sum = 0;
- while(!q.empty()) {
- int c = q.front();
- q.pop();
- for(int i = 0; i < (int) graph[c].size(); i++) {
- int neighbour = graph[c][i].first;
- int weight = graph[c][i].second;
- if(!visited[neighbour]) {
- cout << weight << " " << neighbour << " ";
- visited[neighbour] = true;
- q.push(neighbour);
- sum += weight;
- mapa[neighbour] = sum;
- }
- }
- }
- cout << endl;
- }
- }
- for(pair<int, int> m : mapa) {
- cout << m.first << " " << m.second << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement