/* Author : Mychecksdead  */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 1500+100, M = 1e5+10, K = 52, MX = 30;
const ll INF = 1e18;
int n;
ll dp[N][N];
array<ll, 2> a[N];
void solve(){
  cin >> n;
  ll ans = 0;
  vector<array<int, 2>> pt(n + 1);
  for(int i = 1; i <= 2*n; ++i){
    cin >> a[i][0] >> a[i][1];
    if(a[i][0] < 1){
      ans += 1 - a[i][0];
      a[i][0] = 1;
    }
    if(a[i][0] > n){
      ans += a[i][0] - n;
      a[i][0] = n;
    }
    if(a[i][1] < 1){
      ans += 1 - a[i][1];
      a[i][1] = 1;
    }
    if(a[i][1] > 2){
      ans += a[i][1] - 2;
      a[i][1] = 2;
    }
    pt[a[i][0]][a[i][1] - 1]++;
    // cerr << a[i][0] << ' ' << a[i][1] << '\n';
  }
  array<ll, 4> x = {0ll};
  for(int i = 1; i <= n; ++i){
    for(int j = 1; j <= 2; ++j){
      x[j] += pt[i][j - 1] - 1;
    }
    for(int j = 1; j <= 2; ++j){
      if(x[j] > 0 && x[3 - j] < 0){
        ll val = min(x[j], - x[3 - j]);
        x[j] -= val;
        x[3 - j] += val;
        ans += val;
      }
    }
    ans += abs(x[1]) + abs(x[2]);
  }
  
  cout << ans;
}
int main(){
  cin.tie(0); ios::sync_with_stdio(0);
  int tt = 1, aa;
  // freopen("in.txt", "r", stdin);
  // freopen("out.txt", "w", stdout);
  while(tt--){
    solve();
    en;
  }
  cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
  return 0;
} 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |