Advertisement
jeff69

Brackets

Nov 18th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef int64_t ll;
  4. const int MX=2e5+6;
  5. int dp[55][55];
  6. string h;
  7. bool balanced(int x,int y)
  8. {
  9.     if(h[x]=='('&&h[y]==')')return 1;
  10.     if(h[x]=='['&&h[y]==']')return 1;
  11.     if(x==y)return 1;
  12.     return 0;
  13. }
  14. int correct(int x,int y)
  15. {
  16.     if(h[x]=='('||h[x]=='[')return 1;
  17.     if(h[y]==']'||h[y]==')')return 1;
  18.     return 2;
  19. }
  20. int solve(int l=0,int r=(int)h.size()-1)
  21. {
  22.     if(r-l==-1)return 0;
  23.     if(r<l)return 1e5;
  24.     if(l==r)return 1e5;
  25.     if(dp[l][r]!=-1)return dp[l][r];
  26.     int ans=1e5;
  27.     if(balanced(l,r))ans=min(ans,solve(l+1,r-1));
  28.     if(!balanced(l,r))ans=min(ans,correct(l,r)+solve(l+1,r-1));
  29.     for(int i=l+1;i<r;i++)
  30.     {
  31.         if(balanced(l,i)&&balanced(i+1,r))
  32.         {
  33.             ans=min(ans,solve(l,i)+solve(i+1,r));
  34.         }
  35.         if(balanced(l,i)&&!balanced(i+1,r))
  36.         {
  37.             ans=min(ans,solve(l,i)+solve(i+1,r)+correct(i+1,r));
  38.         }
  39.         if(!balanced(l,i)&&balanced(i+1,r))
  40.         {
  41.             ans=min(ans,solve(l,i)+solve(i+1,r)+correct(l,i));
  42.         }
  43.         if(!balanced(l,i)&&!balanced(i+1,r))
  44.         {
  45.             ans=min(ans,solve(l,i)+solve(i+1,r)+correct(l,i)+correct(i+1,r));
  46.         }
  47.     }
  48.     return dp[l][r]=ans;
  49. }
  50.  int main()
  51. {
  52.     memset(dp,-1,sizeof dp);
  53.     cin>>h;
  54.     cout<<solve();
  55.    return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement