제출 #845056

#제출 시각아이디문제언어결과실행 시간메모리
845056tch1cherinPalembang Bridges (APIO15_bridge)C++17
22 / 100
104 ms15448 KiB
#include <bits/stdc++.h> #define int long long using namespace std; struct fenwick { int size; vector<long long> tree; fenwick(int N) : size(N), tree(N + 1) {} void update(int i, int value) { for (i++; i <= size; i += i & -i) { tree[i] += value; } } long long query(int r) { long long ans = 0; for (; r > 0; r -= r & -r) { ans += tree[r]; } return ans; } int lower_bound(long long value) { int pos = 0; for (int l = 20; l >= 0; l--) { if (pos + (1 << l) <= size && tree[pos + (1 << l)] < value) { pos += (1 << l); value -= tree[pos]; } } return pos; } }; int32_t main() { cin.tie(nullptr)->sync_with_stdio(false); int K, N; cin >> K >> N; vector<char> P(N), Q(N); vector<int> S(N), T(N), G; long long ans = 0; vector<array<int, 2>> X; for (int i = 0; i < N; i++) { cin >> P[i] >> S[i] >> Q[i] >> T[i]; if (P[i] > Q[i]) { swap(S[i], T[i]); } if (P[i] == Q[i]) { ans += abs(S[i] - T[i]); } else { ans++; X.push_back({S[i], T[i]}); G.push_back(S[i]); G.push_back(T[i]); } } int M = (int)X.size(); sort(G.begin(), G.end()); G.resize(unique(G.begin(), G.end()) - G.begin()); vector<int> Y = G; for (int &v : Y) { v = lower_bound(G.begin(), G.end(), v) - G.begin(); } vector<array<int, 2>> C(M); for (int i = 0; i < M; i++) { C[i][0] = lower_bound(G.begin(), G.end(), X[i][0]) - G.begin(); C[i][1] = lower_bound(G.begin(), G.end(), X[i][1]) - G.begin(); } vector<int> ord(M); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int i, int j) { return X[i][0] + X[i][1] < X[j][0] + X[j][1]; }); fenwick FA(M), FB(M); vector<long long> pref(M + 1); long long sum = 0; for (int i = 0; i < M; i++) { for (int j = 0; j < 2; j++) { FA.update(C[ord[i]][j], 1); FB.update(C[ord[i]][j], X[ord[i]][j]); sum += X[ord[i]][j]; } int Ymed = FA.lower_bound(i + 1); int med = G[lower_bound(Y.begin(), Y.end(), Ymed) - Y.begin()]; int cnt = FA.query(Ymed), Sless = FB.query(Ymed); pref[i + 1] = 1LL * med * cnt - Sless + sum - Sless - 1LL * med * ((i + 1) * 2 - cnt); } vector<long long> suff(M + 1); FA = FB = fenwick(M); sum = 0; for (int i = M - 1; i >= 0; i--) { for (int j = 0; j < 2; j++) { FA.update(C[ord[i]][j], 1); FB.update(C[ord[i]][j], X[ord[i]][j]); sum += X[ord[i]][j]; } int Ymed = FA.lower_bound(M - i); int med = G[lower_bound(Y.begin(), Y.end(), Ymed) - Y.begin()]; int cnt = FA.query(Ymed), Sless = FB.query(Ymed); suff[i] = 1LL * med * cnt - Sless + sum - Sless - 1LL * med * ((M - i) * 2 - cnt); } long long res = LLONG_MAX; for (int i = 0; i <= M; i++) { if (i == 0 || K != 1) { res = min(res, pref[i] + suff[i]); } } cout << ans + res << "\n"; }
#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...