結果
問題 |
No.3148 Min-Cost Destruction of Parentheses
|
ユーザー |
|
提出日時 | 2025-05-17 02:40:38 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 47 ms / 4,000 ms |
コード長 | 1,817 bytes |
コンパイル時間 | 2,240 ms |
コンパイル使用メモリ | 214,308 KB |
実行使用メモリ | 9,432 KB |
最終ジャッジ日時 | 2025-05-17 02:40:43 |
合計ジャッジ時間 | 4,162 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 31 |
ソースコード
#include <bits/stdc++.h> using namespace std; class UnionFind{ private: vector<int> par,siz; public: UnionFind(int N){par.resize(N,-1);} int root(int x){ //連結成分の代表頂点を返す. if(par.at(x) == -1) return x; else return par.at(x) = root(par.at(x)); } bool unite(int u, int v){ //u,vを連結する 連結してた->false,した->trueを返す. u = root(u),v = root(v); if(u == v) return false; par.at(u) = v; return true; } bool issame(int u, int v){ //同じ連結成分ならtrue. if(root(u) == root(v)) return true; else return false; } }; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; string s; cin >> s; vector<int> par(N+1,-1); int idx = 0; stack<int> St; St.push(idx); for(auto c : s){ if(c == '('){ idx++; par.at(idx) = St.top(); St.push(idx); } else St.pop(); } vector<long long> A(N+1),B(N+1,1); for(int i=1; i<=N; i++) cin >> A.at(i); using T = tuple<long long,long long,int>; auto comp = [&](const T &a,const T &b) -> bool { auto [x,y,p] = a; auto [x2,y2,q] = b; return x*y2 < x2*y; }; priority_queue<T,vector<T>,decltype(comp)> Q(comp); for(int i=1; i<=N; i++) Q.push({A.at(i),B.at(i),i}); UnionFind Z(N+1); long long answer = 0; while(Q.size()){ auto [a,b,pos] = Q.top(); Q.pop(); if(A.at(pos) != a || B.at(pos) != b) continue; Z.unite(pos,par.at(pos)); int leader = Z.root(pos); long long &a2 = A.at(leader),&b2 = B.at(leader); answer += b2*a; a2 += a; b2 += b; if(leader != 0) Q.push({a2,b2,leader}); } cout << answer << endl; }