結果
| 問題 |
No.3148 Min-Cost Destruction of Parentheses
|
| コンテスト | |
| ユーザー |
hitonanode
|
| 提出日時 | 2025-08-05 00:16:44 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 92 ms / 4,000 ms |
| コード長 | 23,165 bytes |
| コンパイル時間 | 3,305 ms |
| コンパイル使用メモリ | 258,476 KB |
| 実行使用メモリ | 20,604 KB |
| 最終ジャッジ日時 | 2025-08-05 00:16:50 |
| 合計ジャッジ時間 | 6,349 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 31 |
ソースコード
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
const std::vector<std::pair<int, int>> grid_dxs{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <class T1, class T2> T1 floor_div(T1 num, T2 den) { return (num > 0 ? num / den : -((-num + den - 1) / den)); }
template <class T1, class T2> std::pair<T1, T2> operator+(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first + r.first, l.second + r.second); }
template <class T1, class T2> std::pair<T1, T2> operator-(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first - r.first, l.second - r.second); }
template <class T> std::vector<T> sort_unique(std::vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <class T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <class T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <class IStream, class T> IStream &operator>>(IStream &is, std::vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec);
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr);
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const pair<T, U> &pa);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa);
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp);
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp);
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
template <class... T> std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; }
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl
#define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl : std::cerr)
#else
#define dbg(x) ((void)0)
#define dbgif(cond, x) ((void)0)
#endif
// Sorted set of integers [0, n)
// Space complexity: (64 / 63) n + O(log n) bit
class fast_set {
static constexpr int B = 64;
int n;
int cnt;
std::vector<std::vector<uint64_t>> _d;
static int bsf(uint64_t x) { return __builtin_ctzll(x); }
static int bsr(uint64_t x) { return 63 - __builtin_clzll(x); }
public:
// 0 以上 n_ 未満の整数が入れられる sorted set を作成
fast_set(int n_) : n(n_), cnt(0) {
do { n_ = (n_ + B - 1) / B, _d.push_back(std::vector<uint64_t>(n_)); } while (n_ > 1);
}
bool contains(int i) const {
assert(0 <= i and i < n);
return (_d.front().at(i / B) >> (i % B)) & 1;
}
void insert(int i) {
assert(0 <= i and i < n);
if (contains(i)) return;
++cnt;
for (auto &vec : _d) {
bool f = vec.at(i / B);
vec.at(i / B) |= 1ULL << (i % B), i /= B;
if (f) break;
}
}
void erase(int i) {
assert(0 <= i and i < n);
if (!contains(i)) return;
--cnt;
for (auto &vec : _d) {
vec.at(i / B) &= ~(1ULL << (i % B)), i /= B;
if (vec.at(i)) break;
}
}
// i 以上の最小要素 なければ default_val
int next(int i, const int default_val) const {
assert(0 <= i and i <= n);
for (auto itr = _d.cbegin(); itr != _d.cend(); ++itr, i = i / B + 1) {
if (i / B >= int(itr->size())) break;
if (auto d = itr->at(i / B) >> (i % B); d) {
i += bsf(d);
while (itr != _d.cbegin()) i = i * B + bsf((--itr)->at(i));
return i;
}
}
return default_val;
}
int next(const int i) const { return next(i, n); }
// i 以下の最小要素 なければ default_val
int prev(int i, int default_val = -1) const {
assert(-1 <= i and i < n);
for (auto itr = _d.cbegin(); itr != _d.cend() and i >= 0; ++itr, i = i / B - 1) {
if (auto d = itr->at(i / B) << (B - 1 - i % B); d) {
i += bsr(d) - (B - 1);
while (itr != _d.cbegin()) i = i * B + bsr((--itr)->at(i));
return i;
}
}
return default_val;
}
// return minimum element (if exists) or `n` (empty)
int min() const { return next(0); }
// return maximum element (if exists) or `-1` (empty)
int max() const { return prev(n - 1); }
int size() const { return cnt; }
bool empty() const { return cnt == 0; }
void clear() {
if (!cnt) return;
cnt = 0;
auto rec = [&](auto &&self, int d, int x) -> void {
if (d) {
for (auto m = _d.at(d).at(x); m;) {
int i = bsf(m);
m -= 1ULL << i, self(self, d - 1, x * B + i);
}
}
_d.at(d).at(x) = 0;
};
rec(rec, _d.size() - 1, 0);
}
};
#include <cassert>
#include <limits>
// Rational number + {infinity(1 / 0), -infiity(-1 / 0), nan(0 / 0)} (有理数)
// Verified: Yandex Cup 2022 Final E https://contest.yandex.com/contest/42710/problems/K
template <class Int, bool AutoReduce = false> struct Rational {
Int num, den; // den >= 0
static constexpr Int my_gcd(Int a, Int b) {
// return __gcd(a, b);
if (a < 0) a = -a;
if (b < 0) b = -b;
while (a and b) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return a + b;
}
constexpr Rational(Int num = 0, Int den = 1) : num(num), den(den) { normalize(); }
constexpr void normalize() noexcept {
if constexpr (AutoReduce) { // reduction
Int g = my_gcd(num, den);
if (g) num /= g, den /= g;
} else {
if (den == 0) {
if (num > 1) num = 1;
if (num < -1) num = -1;
}
}
if (den < 0) num = -num, den = -den; // denominator >= 0
}
constexpr bool is_finite() const noexcept { return den != 0; }
constexpr bool is_infinite_or_nan() const noexcept { return den == 0; }
constexpr Rational operator+(const Rational &r) const noexcept {
if (is_infinite_or_nan() and r.is_infinite_or_nan()) return Rational(num + r.num, 0);
return Rational(num * r.den + den * r.num, den * r.den);
}
constexpr Rational operator-(const Rational &r) const noexcept {
if (is_infinite_or_nan() and r.is_infinite_or_nan()) return Rational(num - r.num, 0);
return Rational(num * r.den - den * r.num, den * r.den);
}
constexpr Rational operator*(const Rational &r) const noexcept {
return Rational(num * r.num, den * r.den);
}
constexpr Rational operator/(const Rational &r) const noexcept {
return Rational(num * r.den, den * r.num);
}
constexpr Rational &operator+=(const Rational &r) noexcept { return *this = *this + r; }
constexpr Rational &operator-=(const Rational &r) noexcept { return *this = *this - r; }
constexpr Rational &operator*=(const Rational &r) noexcept { return *this = *this * r; }
constexpr Rational &operator/=(const Rational &r) noexcept { return *this = *this / r; }
constexpr Rational operator-() const noexcept { return Rational(-num, den); }
constexpr Rational abs() const noexcept { return Rational(num > 0 ? num : -num, den); }
constexpr Int floor() const {
assert(is_finite());
if (num > 0) {
return num / den;
} else {
return -((-num + den - 1) / den);
}
}
constexpr bool operator==(const Rational &r) const noexcept {
if (is_infinite_or_nan() or r.is_infinite_or_nan()) {
return num == r.num and den == r.den;
} else {
return num * r.den == r.num * den;
}
}
constexpr bool operator!=(const Rational &r) const noexcept { return !(*this == r); }
constexpr bool operator<(const Rational &r) const noexcept {
if (is_infinite_or_nan() and r.is_infinite_or_nan())
return num < r.num;
else if (is_infinite_or_nan()) {
return num < 0;
} else if (r.is_infinite_or_nan()) {
return r.num > 0;
} else {
return num * r.den < den * r.num;
}
}
constexpr bool operator<=(const Rational &r) const noexcept {
return (*this == r) or (*this < r);
}
constexpr bool operator>(const Rational &r) const noexcept { return r < *this; }
constexpr bool operator>=(const Rational &r) const noexcept {
return (r == *this) or (r < *this);
}
constexpr explicit operator double() const noexcept { return (double)num / (double)den; }
constexpr explicit operator long double() const noexcept {
return (long double)num / (long double)den;
}
template <class OStream> constexpr friend OStream &operator<<(OStream &os, const Rational &x) {
return os << x.num << '/' << x.den;
}
};
template <class Int> struct std::numeric_limits<Rational<Int, false>> {
static constexpr Rational<Int, false> max() noexcept {
return std::numeric_limits<Int>::max();
}
static constexpr Rational<Int, false> min() noexcept {
return std::numeric_limits<Int>::min();
}
static constexpr Rational<Int, false> lowest() noexcept {
return std::numeric_limits<Int>::lowest();
}
};
using rat = Rational<lint, false>;
#include <algorithm>
#include <numeric>
#include <utility>
#include <vector>
// UnionFind Tree (0-indexed), based on size of each disjoint set
struct UnionFind {
std::vector<int> par, cou;
UnionFind(int N = 0) : par(N), cou(N, 1) { iota(par.begin(), par.end(), 0); }
int find(int x) { return (par[x] == x) ? x : (par[x] = find(par[x])); }
bool unite(int x, int y) {
x = find(x), y = find(y);
if (x == y) return false;
if (cou[x] < cou[y]) std::swap(x, y);
par[y] = x, cou[x] += cou[y];
return true;
}
int count(int x) { return cou[find(x)]; }
bool same(int x, int y) { return find(x) == find(y); }
std::vector<std::vector<int>> groups() {
std::vector<std::vector<int>> ret(par.size());
for (int i = 0; i < int(par.size()); ++i) ret[find(i)].push_back(i);
ret.erase(std::remove_if(ret.begin(), ret.end(),
[&](const std::vector<int> &v) { return v.empty(); }),
ret.end());
return ret;
}
};
// "01 on Tree"
// just idea: 木構造を持っておいて部分木毎に解く?
// とりあえず部分木毎に目的関数は出せる?
// モノイドを載せる?
using T = long long;
std::pair<std::vector<int>, T>
MinimizeTreePopInversion(const std::vector<std::vector<int>> &to, const std::vector<T> &xs,
const std::vector<T> &ys, int root) {
// for (auto x : dxs) assert(x >= 0);
struct Vec {
T x, y;
Vec(T x, T y) : x(x), y(y) {}
Vec() : x(0), y(0) {}
bool operator<(const Vec &r) const {
if (x == 0 and y == 0) return false;
if (r.x == 0 and r.y == 0) return true;
if (x == 0 and r.x == 0) return y < r.y;
if (x == 0) return false;
if (r.x == 0) return true;
return y * r.x < x * r.y; // be careful of overflow
}
bool operator>(const Vec &r) const { return r < *this; }
void operator+=(const Vec &r) { x += r.x, y += r.y; }
};
const int N = to.size();
std::vector<Vec> first_slope(N);
std::vector<int> par(N, -1);
using Pque = std::priority_queue<Vec, std::vector<Vec>, std::greater<Vec>>;
auto rec = [&](auto &&self, int now, int prv) -> Pque {
std::vector<Pque> chs;
for (int nxt : to[now]) {
if (nxt == prv) continue;
assert(par[nxt] == -1);
par[nxt] = now;
chs.emplace_back(self(self, nxt, now));
}
const Vec v(xs.at(now), ys.at(now));
if (chs.empty()) {
first_slope[now] = v;
Pque pq;
pq.emplace(v);
return pq;
} else {
Vec first = v;
const int idx =
std::max_element(chs.begin(), chs.end(),
[](const auto &a, const auto &b) { return a.size() < b.size(); }) -
chs.begin();
std::swap(chs[idx], chs.front());
for (int i = 1; i < (int)chs.size(); ++i) {
// while (!chs[i].empty() and chs[i].top() < first) {
// first += chs[i].top();
// chs[i].pop();
// }
while (!chs[i].empty()) {
chs.front().emplace(chs[i].top());
chs[i].pop();
}
}
while (!chs.front().empty() and chs.front().top() < first) {
first += chs.front().top();
chs.front().pop();
}
first_slope[now] = first;
chs.front().emplace(first);
return std::move(chs.front());
}
};
rec(rec, root, -1);
std::priority_queue<std::pair<Vec, int>, std::vector<std::pair<Vec, int>>,
std::greater<std::pair<Vec, int>>>
pq;
pq.emplace(first_slope.at(root), root);
std::vector<int> order;
long long ret = 0, y = 0;
while (!pq.empty()) {
const int idx = pq.top().second;
order.emplace_back(idx);
pq.pop();
ret += y * xs.at(idx);
y += ys.at(idx);
for (int nxt : to.at(idx)) {
if (nxt == par.at(idx)) continue;
pq.emplace(first_slope.at(nxt), nxt);
}
}
return {order, ret};
}
lint solve() {
int N;
string str;
cin >> N >> str;
vector<vector<int>> child(N + 1);
{
vector<int> stk{0};
int openid = 1;
for (auto c : str) {
if (c == '(') {
stk.push_back(openid++);
} else {
int v = stk.back();
stk.pop_back();
if (stk.size()) child.at(stk.back()).push_back(v);
}
}
}
vector<long long> A(N);
cin >> A;
A.insert(A.begin(), 0);
dbg(A);
vector<long long> dx(A.size(), 1);
dx.at(0) = 0;
auto seq = MinimizeTreePopInversion(child, A, dx, 0).first;
dbg(seq);
reverse(ALL(seq));
{
lint dy = 0, ans = 0;
for (int i : seq) {
if (i == 0) break;
dy += A.at(i);
ans += dy;
}
return ans;
}
// dbg(res + accumulate(ALL(A), 0LL));
// return res + accumulate(ALL(A), 0LL);
using T = tuple<rat, int, lint>; // (傾き, 要素数, 重みつき和)
using S = multiset<T>;
auto rec = [&](auto &&self, int now) -> S {
if (child.at(now).empty()) {
// vector<int> ret = {A.at(now)};
S ans;
ans.emplace(rat(A.at(now), 1), 1, 0);
return ans;
}
vector<S> children;
for (int nxt : child.at(now)) {
auto r = self(self, nxt);
children.emplace_back(std::move(r));
}
int max_idx = 0;
FOR(i, 1, children.size()) {
if (children.at(i).size() > children.at(max_idx).size()) max_idx = i;
}
std::swap(children.at(max_idx), children.front());
FOR(i, 1, children.size()) {
for (auto x : children.at(i)) { children.front().emplace(x); }
}
children.resize(1);
int addn = 1;
int addsum = A.at(now);
lint addws = 0;
while (children.front().size()) {
auto [slope, n, ws] = *prev(children.front().end());
if (slope >= rat(addsum, addn)) {
children.front().erase(prev(children.front().end()));
auto sumr = slope * n;
const lint sum = sumr.num / sumr.den;
addws += addn * sum + ws;
addn += n;
addsum += sum;
} else {
break;
}
}
children.front().emplace(rat(addsum, addn), addn, addws);
return std::move(children.front());
};
auto ret = rec(rec, 0);
vector<T> retv;
for (auto x : ret) { retv.emplace_back(x); }
reverse(ALL(retv));
dbg(retv);
lint ans = 0;
dbg(retv);
lint cs = 0;
int ndone = 0;
REP(t, retv.size()) {
auto [r, n, ws] = retv.at(t);
const rat sumr = r * n;
const lint sum = sumr.num / sumr.den;
ans += ws + ndone * sum;
ndone += n;
cs += sum;
}
dbg(ans);
return ans;
}
int main() {
cout << solve() << '\n';
// int N;
// string S;
// cin >> N >> S;
// vector<int> A(N);
// cin >> A;
// dbg(make_tuple(S, A));
// fast_set fs(N * 2);
// REP(i, N * 2) fs.insert(i);
// vector<int> indices(N * 2, -1);
// vector<int> id2left(N, -1), id2right(N, -1);
// {
// int openid = 0;
// vector<int> stk;
// REP(i, N * 2) {
// if (S.at(i) == '(') {
// indices.at(i) = openid;
// id2left.at(openid) = i;
// stk.push_back(openid);
// openid++;
// } else {
// indices.at(i) = stk.back();
// id2right.at(stk.back()) = i;
// stk.pop_back();
// }
// }
// }
// dbg(indices);
// priority_queue<pint> pq;
// REP(i, N * 2 - 1) {
// if (S.at(i) == '(' and S.at(i + 1) == ')') {
// const int idx = indices.at(i);
// pq.emplace(A.at(idx), idx);
// }
// }
// lint ret = 0;
// lint X = 0;
// while (pq.size()) {
// auto [a, idx] = pq.top();
// pq.pop();
// const int left = id2left.at(idx);
// const int right = id2right.at(idx);
// if (!fs.contains(left)) continue;
// X += a;
// ret += X;
// fs.erase(left);
// fs.erase(right);
// const int ll = fs.prev(left), rr = fs.next(right);
// if (ll >= 0 and rr < N * 2 and indices.at(ll) == indices.at(rr)) {
// const int idx2 = indices.at(ll);
// pq.emplace(A.at(idx2), idx2);
// }
// }
// cout << ret << '\n';
}
hitonanode