Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- 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);
- }
- 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++;
- }
- }
- ll res = 0;
- cnt = 1;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- if(cnt != mat[i][j]) {
- int tmp = cnt;
- pair<int, int> c = make_pair(i, j);
- while(mat[c.first][c.second] != cnt) {
- res += dist(c.first, c.second, idx[mat[c.first][c.second]].first, idx[mat[c.first][c.second]].second);
- c = idx[mat[c.first][c.second]];
- }
- }
- cnt++;
- }
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement