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;
- int dist(int si, int sj, int ei, int ej) {
- return abs(si - ei) + abs(sj - ej);
- }
- pair<int, int> idx[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] = {i, j};
- cnt++;
- }
- }
- cnt = 1;
- ll res = 0;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- if(cnt != mat[i][j]) {
- pair<int, int> p = {i, j};
- while(cnt != mat[p.first][p.second]) {
- res += dist(p.first, p.second, idx[mat[p.first][p.second]].first, idx[mat[p.first][p.second]].second);
- p = idx[mat[p.first][p.second]];
- }
- }
- cnt++;
- }
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement