Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <map>
- #include <fstream>
- #include <cstring>
- 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];
- //vector<pair<int, int>> graph[maxn];
- int pref_sum[maxn];
- int cords[maxn];
- int mat[10001][10001];
- bool visited[maxn];
- int main() {
- // ifstream cin("in.txt");
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- memset(visited, false, sizeof visited);
- int r, c;
- cin >> r >> c;
- ll res = 0;
- 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;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- if(cnt != mat[i][j]) {
- pair<int, int> c = make_pair(i, j);
- if(!visited[cnt]) {
- bool ok = false;
- // cout << cnt << endl;
- int sum = 0;
- while(!ok) {
- if(mat[c.first][c.second] == cnt) {
- ok = true;
- }
- if(visited[mat[c.first][c.second]]) {
- break;
- }
- visited[mat[c.first][c.second]] = true;
- sum += dist(c.first, c.second, idx[mat[c.first][c.second]].first, idx[mat[c.first][c.second]].second);
- pref_sum[mat[c.first][c.second]] = sum;
- cords[mat[c.first][c.second]] = cnt;
- c = idx[mat[c.first][c.second]];
- if(ok) {
- break;
- }
- }
- // cout << cnt << " " << sum << endl;
- pref_sum[cnt] = sum;
- visited[cnt] = true;
- }
- }
- cnt++;
- }
- }
- cnt = 1;
- for(int i = 0; i < r; i++) {
- for(int j = 0; j < c; j++) {
- int a = mat[i][j];
- int b = cnt;
- if(a != b) {
- if(cords[a] == b) {
- res += pref_sum[b] - pref_sum[a];
- }
- else {
- res += pref_sum[cords[a]] - pref_sum[a] + pref_sum[b];
- // cout << cords[a] << " " << pref_sum[cords[a]] << " " << pref_sum[a] << " " << pref_sum[b] << endl;
- // cout << b << " " << a << " " << pref_sum[cords[a]] - pref_sum[a] + pref_sum[b] << endl;
- }
- // break;
- }
- cnt++;
- }
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement