結果
| 問題 |
No.3148 Min-Cost Destruction of Parentheses
|
| コンテスト | |
| ユーザー |
shinchan
|
| 提出日時 | 2025-05-19 03:11:21 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 94 ms / 4,000 ms |
| コード長 | 2,333 bytes |
| コンパイル時間 | 2,463 ms |
| コンパイル使用メモリ | 215,764 KB |
| 実行使用メモリ | 14,364 KB |
| 最終ジャッジ日時 | 2025-05-19 03:11:28 |
| 合計ジャッジ時間 | 5,752 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 31 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
#define all(v) (v).begin(),(v).end()
#define pb(a) push_back(a)
#define rep(i, n) for(int i=0;i<n;i++)
#define foa(e, v) for(auto&& e : v)
using ll = long long;
const ll MOD7 = 1000000007, MOD998 = 998244353, INF = (1LL << 60);
#define dout(a) cout<<fixed<<setprecision(10)<<a<<endl;
struct node {
ll x, y;
bool operator<( const node& right ) const {
return y * right.x < x * right.y;
}
node& operator+=(const node& v) { x += v.x; y += v.y; return *this;}
node operator+(const node& v) const { return node(*this) += v;}
};
set<pair<node, int>> st;
ll ans = 0;
struct UnionFind {
vector<int> par, p;
vector<node> c;
UnionFind(vector<int> _p, vector<ll> _v) {
int n = _p.size();
par.resize(n, -1);
p = _p;
c.resize(n);
rep(i, n) {
if(i) {
c[i] = node{_v[i], 1LL};
st.insert({c[i], i});
} else c[i] = node{0, 0};
}
}
int root(int x) {
if (par[x] < 0) return x;
else return par[x] = root(par[x]);
}
void merge(int x) {
x = root(x);
int p_leader = root(p[x]);
ans += c[p_leader].y * c[x].x;
bool pflag = (p[p_leader] != -1);
if(pflag) st.erase({c[p_leader], p_leader});
if(size(x) < size(p_leader)) swap(x, p_leader);
else p[x] = p[p_leader];
c[x] += c[p_leader];
par[x] += par[p_leader];
par[p_leader] = x;
if(pflag) st.insert({c[x], x});
return;
}
int size(int x) {
return -par[root(x)];
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
ll n; cin >> n;
string s; cin >> s;
s = "(" + s + ")";
int m = n * 2 + 2;
vector<int> p(n + 1, -1);
int idx = 1;
auto dfs = [&](auto dfs, int i, int par) -> int {
while(i < m and s[i] == '(') {
p[idx ++] = par;
i = dfs(dfs, i + 1, idx - 1) + 1;
}
return i;
};
dfs(dfs, 1, 0);
vector<ll> v(n + 1);
rep(i, n) cin >> v[i + 1];
UnionFind uf(p, v);
while(!st.empty()) {
auto [P, id] = *st.begin();
st.erase(st.begin());
uf.merge(id);
}
cout << ans + accumulate(all(v), 0LL) << endl;
return 0;
}
shinchan