1070. 括号配对


题目链接

1070. 括号配对

Hecy 又接了个新任务:BE 处理。

BE 中有一类被称为 GBE。

以下是 GBE 的定义:

  • 空表达式是 GBE

  • 如果表达式 A 是 GBE,则 [A] 与 (A) 都是 GBE

  • 如果 A 与 B 都是 GBE,那么 AB 是 GBE

下面给出一个 BE,求至少添加多少字符能使这个 BE 成为 GBE。

注意:BE 是一个仅由()[]四种字符中的若干种构成的字符串。

输入格式

输入仅一行,为字符串 BE。

输出格式

输出仅一个整数,表示增加的最少字符数。

数据范围

对于所有输入字符串,其长度小于100。

输入样例:

[])

输出样例:

1

解题思路

区间dp

可以转换为求最大合法子序列

  • 状态表示:\(f[i][j]\) 表示区间 \([i,j]\) 内的最大合法长度

  • 状态计算:

    • \(s[i]\)\(s[j]\) 匹配时,\(f[i][j]=max(f[i][j],2+f[i+1][j-1])\),但这种情况不是绝对的,可能存在这样的情况:()(),需要考虑下面这种情况
    • 反之,枚举分界点取最大,即 \(f[i][j]=max(f[i][j],f[i][k]+f[k+1][j])\)
  • 时间复杂度:\(O(n^3)\)

代码

// Problem: 括号配对
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/1072/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include 
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair PII;
typedef pair PLL;
 
template  bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template  bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template  void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=105;
string s;
int n,f[N][N];
bool ck(char a,char b)
{
	if(a=='('&&b==')'||a=='['&&b==']')return true;
	return false;
}
int main()
{
    cin>>s;
    n=s.size();
    s=' '+s;
    for(int len=2;len<=n;len++)
		for(int l=1;l+len-1<=n;l++)
		{
			int r=l+len-1;
			if(ck(s[l],s[r]))f[l][r]=max(f[l][r],2+f[l+1][r-1]);
			for(int k=l;k