Poj2955brackets interval DP (bracket matching)

Source: Internet
Author: User

First consider how to define the DP so that it satisfies having a sub-structure to solve,
define DP [i] [j] as the number I to the J bracket in the string maximum match
Then if we know the maximum match of the I to J interval, then the i+1 to the j+1 interval is not Can be very simple to get.
So if the first and the first J are a pair of matching parentheses then DP [i] [j] = DP [i+1] [j-1] + 2;
then we just need to enumerate all the parentheses in the middle of all I and j from small to large, then satisfy the match with the above formula DP, and then update DP [i] [j] to the maximum value each time.
The method of updating the maximum value is to enumerate the intermediate values of I and J, and then let dp[i] [j] = max (DP [i] [j], DP [i] [f] + DP [f+1] [j]);

 for the first time with string, feel good, think this thing is a try to use, never to the process #include <iostream> #include <algorithm
> #include <string.h> using namespace std;
string S;
int dp[105][105]; int main () {while (cin>>s) {if (s== "end")//can also be written here s[0]== ' E ', s.length () can also be written s.size () Brea
            K
            Memset (Dp,0,sizeof (DP)); for (int i=1;i<=s.length (), i++) for (int j=0,k=i;k<s.length (); j++,k++) {i F (s[j]== ' (' &&s[k]== ') ' | |
                s[j]== ' [' &&s[k]== '] ') dp[j][k]=dp[j+1][k-1]+2;
            for (int m=j;m<k;m++) Dp[j][k]=max (Dp[j][k],dp[j][m]+dp[m+1][k]);
    } cout<<dp[0][s.length () -1]<<endl;
} return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.