#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define st first
#define nd second
typedef long long ll;
typedef long double ld;
const ll I = 1'000'000'000'000'000'000LL;
const int II = 2'000'000'000;
const ll M = 1'000'000'007LL;
const int N = 1<<18;
const int K = 1000;
pair<int, int> co[N];
vector<int> pos[2];
vector<pair<pair<int, int>, ll>> dp[N];
int tab[N];
ll A(int a, int b)
{
if(a > b) return a - b;
return b - a;
}
void Gen(int a, int b, int n, int m, ll d)
{
int p = (a + b) / 2 + 1;
ll o;
// cout << "G: " << p << " " << a << " " << b << " " << d << "\n";
if(a < n && b < m)
{
o = d + A(pos[0][a], p) + A(p, pos[1][b]);
dp[p].pb(make_pair(make_pair(a + 1, b + 1), o));
}
if(a < n - 1)
{
o = d + A(pos[0][a], p) + A(pos[0][a + 1], p) + 1LL;
dp[p].pb(make_pair(make_pair(a + 2, b), o));
}
if(b < m - 1)
{
o = d + A(pos[1][b], p) + A(pos[1][b + 1], p) + 1LL;
dp[p].pb(make_pair(make_pair(a, b + 2), o));
}
}
ll Dijsktra()
{
priority_queue<pair<ll, pair<int, int> >> q;
int n = pos[0].size(), m = pos[1].size();
dp[0].pb(make_pair(make_pair(0, 0), 0LL));
for(int i = 0; i < (n + m) / 2; ++i)
{
sort(dp[i].begin(), dp[i].end());
vector<pair<ll, pair<int, int>>> cur;
for(int j = 0; j < (int)dp[i].size(); ++j)
if(j == 0 || dp[i][j].st != dp[i][j - 1].st)
cur.pb(make_pair(dp[i][j].nd, dp[i][j].st));
dp[i].clear();
sort(cur.begin(), cur.end());
for(int j = 0; j < (int)cur.size() && cur[j].st <= cur[0].st + 5LL; ++j)
Gen(cur[j].nd.st, cur[j].nd.nd, n, m, cur[j].st);
}
ll ans = I;
int lim = (n + m) / 2;
for(int i = 0; i < (int)dp[lim].size(); ++i)
ans = min(ans, dp[lim][i].nd);
return ans;
}
void Solve()
{
int n;
ll answer = 0LL;
cin >> n;
for(int i = 1; i <= 2 * n; ++i)
{
cin >> co[i].st >> co[i].nd;
if(co[i].st < 1)
{answer += 1 - co[i].st; co[i].st = 1;}
if(co[i].st > n)
{answer += co[i].st - n; co[i].st = n;}
if(co[i].nd < 1)
{answer += 1 - co[i].nd; co[i].nd = 1;}
if(co[i].nd > 2)
{answer += co[i].nd - 2; co[i].nd = 2;}
// cout << "I: " << co[i].st << " " << co[i].nd << "\n";
pos[co[i].nd - 1].pb(co[i].st);
}
sort(pos[0].begin(), pos[0].end());
sort(pos[1].begin(), pos[1].end());
ll ans = Dijsktra();
ans += answer;
cout << ans << "\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
//int t; cin >> t;
//while(t--)
Solve();
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... |