#include <bits/stdc++.h>
using namespace std;
int czyDobry[301][301];
int ileDobrych[301][301];
int main(){
ios_base::sync_with_stdio(0);
int n, k; cin>>n>>k;
string s; cin>>s;
vector<vector<int>> dp(n+1, vector<int>(k+1, 1e9));
for(int dlg = 1; dlg <= n; dlg++){
for(int i = 0; i < n-dlg; i++){
if(s[i]=='('&&s[i+dlg]==')'){
if(dlg==1) czyDobry[i][i+dlg] = true;
else if(czyDobry[i+1][i+dlg-1]){
czyDobry[i][i+dlg] = true;
}else{
for(int j = i+1; j < i+dlg; j++){
if(czyDobry[i][j]&&czyDobry[j+1][i+dlg]){
czyDobry[i][i+dlg] = true;
break;
}
}
}
}
}
}
for(int dlg = 1; dlg <= n; dlg++){
for(int i = 0; i < n-dlg; i++){
ileDobrych[i][i+dlg] = ileDobrych[i][i+dlg-1];
for(int j = i; j < i+dlg; j++){
if(czyDobry[j][i+dlg]) ileDobrych[i][i+dlg]++;
}
}
}
for(int i = 0; i < n; i++){
for(int j = i; j>=0; j--){
for(int p = 0; p <= k; p++){
if(j>0&&p>0) dp[i][p] = min(dp[i][p], dp[j-1][p-1]+ileDobrych[j][i]);
else dp[i][p] = min(dp[i][p], ileDobrych[0][i]);
}
}
}
cout<<dp[n-1][k-1]<<'\n';
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #include <bits/stdc++.h> using namespace std; int czyDobry[301][301]; int ileDobrych[301][301]; int main(){ ios_base::sync_with_stdio(0); int n, k; cin>>n>>k; string s; cin>>s; vector<vector<int>> dp(n+1, vector<int>(k+1, 1e9)); for(int dlg = 1; dlg <= n; dlg++){ for(int i = 0; i < n-dlg; i++){ if(s[i]=='('&&s[i+dlg]==')'){ if(dlg==1) czyDobry[i][i+dlg] = true; else if(czyDobry[i+1][i+dlg-1]){ czyDobry[i][i+dlg] = true; }else{ for(int j = i+1; j < i+dlg; j++){ if(czyDobry[i][j]&&czyDobry[j+1][i+dlg]){ czyDobry[i][i+dlg] = true; break; } } } } } } for(int dlg = 1; dlg <= n; dlg++){ for(int i = 0; i < n-dlg; i++){ ileDobrych[i][i+dlg] = ileDobrych[i][i+dlg-1]; for(int j = i; j < i+dlg; j++){ if(czyDobry[j][i+dlg]) ileDobrych[i][i+dlg]++; } } } for(int i = 0; i < n; i++){ for(int j = i; j>=0; j--){ for(int p = 0; p <= k; p++){ if(j>0&&p>0) dp[i][p] = min(dp[i][p], dp[j-1][p-1]+ileDobrych[j][i]); else dp[i][p] = min(dp[i][p], ileDobrych[0][i]); } } } cout<<dp[n-1][k-1]<<'\n'; return 0; } |
English