結果

問題 No.3148 Min-Cost Destruction of Parentheses
ユーザー shobonvip
提出日時 2025-05-16 23:01:10
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 105 ms / 4,000 ms
コード長 2,561 bytes
コンパイル時間 4,989 ms
コンパイル使用メモリ 259,460 KB
実行使用メモリ 20,832 KB
最終ジャッジ日時 2025-05-16 23:01:19
合計ジャッジ時間 7,467 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #

/**
	author:  shobonvip
	created: 2024.10.19 23:32:12
**/

#include<bits/stdc++.h>
using namespace std;

//* ATCODER
#include<atcoder/all>
using namespace atcoder;
typedef modint998244353 mint;
//*/

/* BOOST MULTIPRECISION
#include<boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
//*/

typedef long long ll;

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)

template <typename T> bool chmin(T &a, const T &b) {
	if (a <= b) return false;
	a = b;
	return true;
}

template <typename T> bool chmax(T &a, const T &b) {
	if (a >= b) return false;
	a = b;
	return true;
}

template <typename T> T max(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]);
	return ret;
}

template <typename T> T min(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]);
	return ret;
}

template <typename T> T sum(vector<T> &a){
	T ret = 0;
	for (int i=0; i<(int)a.size(); i++) ret += a[i];
	return ret;
}

struct S {
	int ind;
	ll siz;
	ll sum;
	ll par;
};

S op(S a, S b){
	if (a.sum * b.siz < b.sum * a.siz) {
		return b;
	}
	if (a.sum * b.siz > b.sum * a.siz) {
		return a;
	}
	if (a.ind < b.ind) return b;
	return a;
}

S e(){
	return {0, 1, 0, -1};
}

void solve(int n, vector<int> p, vector<ll> a) {
	dsu uf(n);
	vector<S> now_ret(n,e());
	now_ret[0] = S{0,1,0,-1};
	segtree<S,op,e> seg(n);
	rep(i,1,n){
		seg.set(i, S{i,1,a[i],p[i]});
		now_ret[i] = S{i,1,a[i],p[i]};
	}

	ll ans = 0;
	rep(num,0,n-1){
		S ret = seg.all_prod();
		int i = ret.ind;
		S X = now_ret[uf.leader(i)];
		S Y = now_ret[uf.leader(X.par)];
		
		seg.set(uf.leader(i),e());
		seg.set(uf.leader(Y.ind),e());
		
		//cout << X.sum << ' ' << X.siz << endl;
 		ans += Y.siz * X.sum;

		uf.merge(i, X.par);
		
		Y.siz += X.siz;
		Y.sum += X.sum;
		Y.ind = uf.leader(i);
		Y.par = min(Y.par, X.par);

		now_ret[uf.leader(i)] = Y;
		if (Y.par != -1) seg.set(uf.leader(i), now_ret[uf.leader(i)]);
	}

	assert(uf.size(0) == n);

	cout << ans << '\n';

}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	int n; cin >> n;
	string s; cin >> s;
	vector<ll> a(n+1);
	rep(i,0,n) cin >> a[i+1];
	vector<int> p(n+1,-1);
	vector<int> st = {0};
	int cnt = 0;
	for (char c:s) {
		if (c=='('){
			cnt++;
			p[cnt]=st.back();
			st.push_back(cnt);
		}else{
			st.pop_back();
		}
	}
	/*
	rep(i,0,n+1)cout<<p[i]<< ' ';
	cout<<endl;
	rep(i,0,n+1)cout<<a[i]<< ' ';
	cout<<endl;
	*/
	solve(n+1,p,a);
}

0