제출 #158501

#제출 시각아이디문제언어결과실행 시간메모리
158501maruiiPalembang Bridges (APIO15_bridge)C++14
100 / 100
126 ms8528 KiB
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
using ll = long long;
#define ff first
#define ss second

int K, N, cnt;
ll pfx[100005], sfx[100005], cost;
pii P[100005];
vector<int> x;

void f(ll *f) {
	priority_queue<pii, vector<pii>, greater<pii> > pq;
	for (int i = 1; i <= N; ++i) x.push_back(P[i].ff), x.push_back(P[i].ss);
	sort(x.begin(), x.end());
	x.erase(unique(x.begin(), x.end()), x.end());
	int s = 0;
	for (int i = 1, j = 0; i <= N; ++i) {
		f[i] = f[i - 1] + 2 * max({0, P[i].ff - x[j], x[j] - P[i].ss});
		pq.emplace(P[i].ff, 2);
		pq.emplace(P[i].ss, 2);
		s -= 2;
		while (pq.size() && pq.top().ff <= x[j]) {
			s += pq.top().ss;
			pq.pop();
		}
		while (s < 0) {
			f[i] += 1ll * s * (x[j + 1] - x[j]);
			j++;
			while (pq.size() && pq.top().ff <= x[j]) {
				s += pq.top().ss;
				pq.pop();
			}
		}
	}
}

int main() {
	ios_base::sync_with_stdio(0), cin.tie(0);
	cin >> K >> N;
	for (int i = 0; i < N; ++i) {
		char a, b; int c, d; cin >> a >> c >> b >> d;
		cost += abs(c - d);
		if (a != b) {
			cost++;
			if (c > d) swap(c, d);
			P[++cnt] = {c, d};
		}
	}
	N = cnt;
	sort(P + 1, P + N + 1, [&](pii a, pii b) { return a.ff + a.ss < b.ff + b.ss; });
	f(pfx);
	if (K < 2) return !printf("%lld\n",pfx[N] + cost);
	reverse(P + 1, P + N + 1);
	for (int i = 1; i <= N; ++i) {
		int t = -P[i].ff;
		P[i].ff = -P[i].ss;
		P[i].ss = t;
	}
	f(sfx);
	ll mn = pfx[N];
	for (int i = 1; i < N; ++i) mn = min(mn, pfx[i] + sfx[N - i]);
	cout << mn + cost;
	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...