POJ 2955 matching brackets interval dp

topic:

The maximum number of matches given string of characters ask brackets

Ideas:

Initialized to 0

1 begins the enumeration ends from the length of each segment of the length of the answer of the determination is not a pair of brackets is then dp [i] [j] = dp [i + 1] [j - 1] + 2

After the determination is completed dp [i] [j] will always take max

AC Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>

using namespace std;

char s[105];
int dp[105][105];

bool check(int a,int b){
	if(s[a] == '(' && s[b] == ')') return 1;
	if(s[a] == '[' && s[b] == ']') return 1;
	return 0;
}

int main()
{
	while(~scanf("%s",s + 1)){
		if(s[1] == 'e') break;
		int n = strlen(s + 1);
		for(int i = 1;i <= n; i++){
			for(int j = 1;j <= n; j++){
				dp[i][j] = 0;
			}
		}
		for(int i = 1;i <= n; i++){//枚举长度
			for(int j = 1;j + i - 1 <= n; j++){//枚举开头
				int L = j + i - 1;
				if(check(j,L)){
					dp[j][L] = dp[j + 1][L - 1] + 2;
				}
				for(int k = j;k < L; k++){
					dp[j][L] = max(dp[j][L],dp[j][k] + dp[k + 1][L]);
				}
			}
		}

		printf("%d\n",dp[1][n]);
	}
}

 

Published 31 original articles · won praise 5 · Views 1370

Guess you like

Origin blog.csdn.net/qq_43685900/article/details/102766127