POJ 1141 Brackets Sequence (linear DP)

Source: Internet
Author: User

Test instructions: A bracket string is given to find the shortest bracket string that satisfies the requirement;

Idea: Enumerate length, enumerate start and end points, find matching parentheses are recursive to sub-sequences, enumerate intermediate pointers for optimal solution, and the shortest sequence can be obtained recursively by memory table path storage optimal solution during printing;

#include <cstdio>#include<cstring>#include<algorithm>#defineINF 0x7fffffffusing namespacestd;Charstr[505];intdp[505][505];intpath[505][505];voidOprint (intIintj) {    if(I&GT;J)return; if(i==j) {if(str[i]=='['|| str[i]==']') printf ("[]"); Elseprintf"()"); }    Else if(path[i][j]==-1) {printf ("%c", Str[i]); Oprint (i+1, J-1); printf ("%c", Str[j]); }    Else{oprint (i,path[i][j]); Oprint (Path[i][j]+1, J); }}intMain () {gets (str); intn=strlen (str); if(n==0) {printf ("\ n");return 0; } memset (Path,0,sizeof(path)); Memset (DP,0,sizeof(DP));  for(intI=0; i<n;i++) Dp[i][i]=1;  for(intR=1; r<=n;r++)//Recursive fader sequence length        {             for(intI=0; i<n-r;i++)//enumeration starting point            {                intJ=i+r;//calculates the end position of a sub-sequencedp[i][j]=0x7fffffff; if((str[i]=='('&&str[j]==')')|| (str[i]=='['&&str[j]==']') ) {Dp[i][j]=dp[i+1][j-1]; } Path[i][j]=-1;//put it on the outside, or WA                 for(intk=i;k<j;k++)//Enumerate intermediate pointers                {                    if(dp[i][j]>dp[i][k]+dp[k+1][j]) {Dp[i][j]=dp[i][k]+dp[k+1][j]; PATH[I][J]=K; } }}} oprint (0, N-1); printf ("\ n"); return 0;}

POJ 1141 Brackets Sequence (linear DP)

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.