This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// In the name of Allah
#include <bits/stdc++.h>
#include "wiring.h"
using namespace std;
typedef		long long int			ll;
typedef		long double				ld;
typedef		pair<int, int>			pii;
typedef		pair<ll, ll>			pll;
typedef		complex<ld>				cld;
#define		all(x)					(x).begin(),(x).end()
#define		len(x)					((ll) (x).size())
#define		F						first
#define		S						second
#define		X						real()
#define		Y						imag()
#define		pb						push_back
#define		sep						' '
#define		endl					'\n'
#define		Mp						make_pair
#define		kill(x)					cout << x << '\n', exit(0)
#define		set_dec(x)				cout << fixed << setprecision(x);
#define		file_io(x,y)			freopen(x, "r", stdin); freopen(y, "w", stdout);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int n, m;
const int maxn = 2e5 + 4;
const ll oo = 1e18 + 4;
vector<pll> adj[maxn];
bool mark[maxn]; ll dp[maxn][2];
void addE(int u, int v, ll w) {
	adj[u].pb(Mp(v, w)); adj[v].pb(Mp(u, w));
}
void dfs(int v) {
	mark[v] = 1;
	ll R = 0; dp[v][0] = 0; dp[v][1] = oo;
	for (auto f : adj[v]) {
		int u = f.F; ll w = f.S;
		if (!mark[u]) {
			dfs(u);
			dp[v][0] += dp[u][1];
			dp[v][1] = min(dp[v][1] + min(dp[u][1], dp[u][0] + w), R + min(dp[u][1], dp[u][0]) + w);
			R += min(dp[u][1], dp[u][0] + w);
		}
	}
}
ll min_total_length(vector<int> r, vector<int> b) {
	n = len(r); m = len(b);
	sort(all(r)); sort(all(b));
	
	for (int i = 0; i < n; i++) {
		int j = lower_bound(all(b), r[i]) - b.begin();
		if (j < len(b)) addE(i, n + j, abs(r[i] - b[j]));
		if (j - 1 >= 0) addE(i, n + j - 1, abs(r[i] - b[j - 1]));
	}
	for (int i = 0; i < m; i++) {
		int j = lower_bound(all(r), b[i]) - r.begin();
		if (j < len(r)) addE(n + i, j, abs(b[i] - r[j]));
		if (j - 1 >= 0) addE(n + i, j - 1, abs(b[i] - r[j - 1]));
	}
	
	for (int i = 0; i < n + m; i++) {
		sort(all(adj[i])); adj[i].resize(unique(all(adj[i])) - adj[i].begin());
	}
	
	ll ans = 0;
	for (int i = 0; i < n + m; i++) {
		if (mark[i]) continue;
		dfs(i); ans += dp[i][1];
	}
	return ans;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |