1. 程式人生 > >NYOJ15-括號匹配(二)-區間DP

NYOJ15-括號匹配(二)-區間DP

dp[i][j]表示從i到j至少需要新增多少個括號才能滿足匹配條件.

初始化:

if(i == j)

   dp[i][j] = 1;

else

   dp[i][j] = INF;

狀態轉移:

當i < j時;

if(match(str[i], str[j])) dp[i][j] = min(dp[i][j], d[i + 1][j - 1]);

然後分割區間, 找最優分割點k. (i <= k <= j);

dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]);

迴圈時, 遍歷區間(i...j)的起點i以及區間長度len, len從小到大依次遞增.

即迴圈找出每一段起點為i長度為len的區間的最優解, 慢慢擴大至整個區間.即最終問題的解!

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <iomanip>
#define CL(x,v); memset(x,v,sizeof(x));
#define INF 1<<29
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

const int N = 100 + 10;
int dp[N][N];
char str[N];

int match(char ch1, char ch2)
{
    if((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2== ']'))
        return 1;
    return 0;
}

int main()
{
	int t;
	scanf("%d", &t);
	while(t--)
    {
        CL(dp, 0);
        scanf("%s", str);
        int length = strlen(str);

        for(int i = 0; i < length; ++i)
            dp[i][i] = 1;
        for(int len = 1; len < length; ++len)
        {
            for(int i = 0; i < length - len; ++i)
            {
                int j = i + len;
                dp[i][j] = INF;

                if(match(str[i], str[j]))
                   dp[i][j] = min(dp[i][j], dp[i + 1][j - 1]);

                for(int k = i; k <= j; ++k)
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]);
            }
        }
        cout << dp[0][length - 1] << endl;
    }
    return 0;
}