結果

問題 No.2591 安上がりな括弧列
ユーザー 👑 potato167potato167
提出日時 2023-12-19 15:05:11
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 3 ms / 2,000 ms
コード長 1,029 bytes
コンパイル時間 2,393 ms
コンパイル使用メモリ 206,380 KB
実行使用メモリ 6,676 KB
最終ジャッジ日時 2023-12-19 15:05:14
合計ジャッジ時間 3,395 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,676 KB
testcase_01 AC 2 ms
6,676 KB
testcase_02 AC 2 ms
6,676 KB
testcase_03 AC 2 ms
6,676 KB
testcase_04 AC 2 ms
6,676 KB
testcase_05 AC 2 ms
6,676 KB
testcase_06 AC 2 ms
6,676 KB
testcase_07 AC 2 ms
6,676 KB
testcase_08 AC 2 ms
6,676 KB
testcase_09 AC 2 ms
6,676 KB
testcase_10 AC 2 ms
6,676 KB
testcase_11 AC 2 ms
6,676 KB
testcase_12 AC 2 ms
6,676 KB
testcase_13 AC 2 ms
6,676 KB
testcase_14 AC 2 ms
6,676 KB
testcase_15 AC 2 ms
6,676 KB
testcase_16 AC 2 ms
6,676 KB
testcase_17 AC 2 ms
6,676 KB
testcase_18 AC 2 ms
6,676 KB
testcase_19 AC 3 ms
6,676 KB
testcase_20 AC 2 ms
6,676 KB
testcase_21 AC 2 ms
6,676 KB
testcase_22 AC 2 ms
6,676 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#pragma GCC optimize("unroll-loops")
using namespace std;
using ll=long long;
#define rep(i,a,b) for (int i=(int)(a);i<(int)(b);i++)

//O(N log(N))
/*
S が長さ 2N の整合された括弧列であることは
以下の条件を全て満たすことと同じ。

- (,) がそれぞれ N 個ずつ含む
- 任意の 1<= i <= N について、
「S の前 (2i-1)文字に '(' が i 個以上存在する」

よって、前から見ていって、奇数文字目のタイミングで
未確定のもののうち、'(' にするコストが1番低いものを '(' で確定させる。
とすると最適になる

これは heap を用いて O(N log(N)) で実装できる

*/
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int N;
	cin>>N;
	priority_queue<ll> pq;
	ll ans=0;
	string S;
	cin>>S;
	rep(i,0,N*2){
		ll a;
		cin>>a;
		if(S[i]=='('){
			ans+=a;
			pq.push(a);
		}
		else{
			pq.push(-a);
		}
		if(i%2==0){
			ans-=pq.top();
			pq.pop();
		}
	}
	cout<<ans<<"\n";
}
0