#include <bits/stdc++.h> using namespace std; const int MXN=100; int dp[MXN][MXN]; int solve(int p, int k, string &s) { if (p>k) { dp[p][k]=0; return 0; } if (dp[p][k]!=-1) return dp[p][k]; solve(p+1, k, s); solve(p, k-1, s); solve(p+1, k-1, s); dp[p][k]=dp[p+1][k]+dp[p][k-1]-dp[p+1][k-1]; int cnt=0, mn=0; for (int i=p; i<=k; i++) { cnt+=(s[i]=='('? 1 : -1); mn=min(mn, cnt); } dp[p][k]+=(cnt==0 && mn==0); return dp[p][k]; } int main() { memset(dp, -1, sizeof(dp)); ios_base::sync_with_stdio(false); cin.tie(NULL); int n, k; cin>>n>>k; string w; cin>>w; //~ while (true) //~ { //~ int x, y; cin>>x>>y; //~ cout<<solve(x, y, w)<<endl; //~ } int ans=INT_MAX; for (int i=1; i<(1<<(n-1)); i++) { if (__builtin_popcount(i)!=k-1) continue; int pre=0, pom=0; for (int j=0; j<n; j++) { if (i&(1<<j)) { pom+=solve(pre, j, w); pre=j+1; } } pom+=solve(pre, n-1, w); ans=min(ans, pom); } cout<<ans<<"\n"; }
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 49 50 51 52 53 54 55 | #include <bits/stdc++.h> using namespace std; const int MXN=100; int dp[MXN][MXN]; int solve(int p, int k, string &s) { if (p>k) { dp[p][k]=0; return 0; } if (dp[p][k]!=-1) return dp[p][k]; solve(p+1, k, s); solve(p, k-1, s); solve(p+1, k-1, s); dp[p][k]=dp[p+1][k]+dp[p][k-1]-dp[p+1][k-1]; int cnt=0, mn=0; for (int i=p; i<=k; i++) { cnt+=(s[i]=='('? 1 : -1); mn=min(mn, cnt); } dp[p][k]+=(cnt==0 && mn==0); return dp[p][k]; } int main() { memset(dp, -1, sizeof(dp)); ios_base::sync_with_stdio(false); cin.tie(NULL); int n, k; cin>>n>>k; string w; cin>>w; //~ while (true) //~ { //~ int x, y; cin>>x>>y; //~ cout<<solve(x, y, w)<<endl; //~ } int ans=INT_MAX; for (int i=1; i<(1<<(n-1)); i++) { if (__builtin_popcount(i)!=k-1) continue; int pre=0, pom=0; for (int j=0; j<n; j++) { if (i&(1<<j)) { pom+=solve(pre, j, w); pre=j+1; } } pom+=solve(pre, n-1, w); ans=min(ans, pom); } cout<<ans<<"\n"; } |