Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #ifdef HORI
- #include "../lib/hori.h"
- #else
- #define debug(...)
- #endif
- #define int int64_t
- using vi = vector<int>;
- #define FOR(i, a, b) for (int i = (a); i < (b); i++)
- #define all(x) x.begin(), x.end()
- #define nl '\n'
- auto vec(auto&& v, int n) {return vector(n, v);}
- auto vec(auto&& v, int n, auto... m) {return vector(n, vec(v, m...));}
- template <class T> concept C = !is_same<T, string>::value && ranges::range<T>;
- template <C T> ostream& operator<<(ostream &os, const T &v) {for (auto x : v) os << x << ' '; return os << nl;}
- template <C T> istream &operator>>(istream &in, T &v) {for (auto& x : v) in >> x; return in;}
- #define L(x, ...) ([&] (auto&& x) -> decltype(auto) {return __VA_ARGS__;})
- template <class... T> void re(T &...a) {(cin >> ... >> a);}
- template <class... T> void pr(T... a) {((cout << ' ' << a), ...);}
- #define def(t, a...) t a; re(a);
- const int oo = 1e18, MX = 2e5;
- void solve() {
- def(int, n);
- vi b(n), w(n); re(b, w);
- int c = 0;
- FOR(i, 0, n) {
- int x = min(w[i], b[i]);
- b[i] -= x, w[i] -= x;
- c += x;
- }
- int ans = oo;
- FOR(_, 0, 2) {
- int cc = c, cnt = n, ind = 0;
- vi sb = b; sort(all(sb));
- int sum_w = accumulate(all(w), 0ll), sum_b = accumulate(all(b), 0ll);
- while (true) {
- int x = (ind < n ? sb[ind] : oo) - (ind == 0 ? 0 : sb[ind - 1]);
- auto eval = [] (int n, int cc, int sum_b, int sum_w) {
- bool g = (sum_b + sum_w) or (cc % (n - 2));
- int s = cc / (n - 2); if (!g and s > 0) s -= 1;
- return sum_b + sum_w + (cc - s * (n - 2)) * 2;
- };
- FOR(i, 0, min(x, n / max<int>(cnt, 1) * 2)) ans = min(ans, eval(n, cc + (cnt - 1) * i, sum_b - cnt * i, sum_w + (n - cnt) * i));
- if (ind < n) FOR(i, 0, min(x, n / max<int>(cnt, 1) * 2)) ans = min(ans, eval(n, cc + (cnt - 1) * (x - i), sum_b - cnt * (x - i), sum_w + (n - cnt) * (x - i)));
- if (cnt == 0) break;
- int pind = ind;
- sum_b -= cnt * x; sum_w += (n - cnt) * x; cc += (cnt - 1) * x;
- while (ind < n and sb[ind] == sb[pind]) cnt--, ind++;
- }
- swap(b, w);
- }
- pr(ans, nl);
- }
- signed main() {
- ios::sync_with_stdio(0); cin.tie(0);
- def(int, t); while (t--)
- solve();
- }
Advertisement
Add Comment
Please, Sign In to add comment