题解:P16142 [ICPC 2017 NAIPC] Pieces of Parentheses
lujiayi654321 · · 题解
Solution
括号匹配的经典套路。设左括号
- 所有括号和为
0 ; - 任意前缀和均
\ge0 。
我们称一个串所有括号和为该串的价值。所以拼好串价值为
例:碎片串
\texttt{()))()(} 中,最小前缀和为-2 ,至少要补一个价值为2 的串以匹配右括号。
考虑 DP。\
定义
我们发现括号顺序是影响前缀和但不影响价值的,因此贪心地把最小前缀和较大和价值较大的串排在前面。详见文末“思考”部分。\
当所有碎片串的最小前缀和都小于
转移是平凡的,类似背包:
其中
答案即为
时间复杂度
Code
:::success[AC Code]
#include <string>
#include <iostream>
#include <algorithm>
#include <cstring>
#define re register
using namespace std;
struct Node {
string s; int sum,pre;
bool operator < (const Node& other) const {
if(sum>0 ^ other.sum>0) return sum>0;
if(sum>0) return pre>other.pre;
return pre-sum<other.pre-other.sum;
}
}s[303];
int f[2][90009];
inline void Max(int &a,int b) {if(a<b) a=b;}
int main()
{
ios::sync_with_stdio(false),cin.tie(0);
int n,V=0; cin>>n;
for(re int i=0;i!=n;++i) {
cin>>s[i].s;
for(auto it=s[i].s.begin();it!=s[i].s.end();++it)
if((s[i].sum+=*it=='('?1:-1)<s[i].pre)
s[i].pre=s[i].sum;
if(s[i].sum>0) V+=s[i].sum;
}
sort(s,s+n);
if(0[s].pre<0) return putchar(48),0;
memset(1[f],-0x3f,sizeof 1[f]),*1[f]=0;
// 初始化为不合法
for(re int i=0;i!=n;++i) {
memcpy(f[i&1],f[i&1^1],(V+1)*sizeof(int));
// 记得 copy 上一轮
if(s[i].sum>0) // 需要仔细分析防止越界
for(re int j=s[i].sum;j<=V;++j) {
if(j-s[i].sum+s[i].pre>=0)
Max(f[i&1][j],f[i&1^1][j-s[i].sum]+s[i].s.size());
}
else
for(re int j=0;j<=V+s[i].sum;++j)
if(j-s[i].sum+s[i].pre>=0)
Max(f[i&1][j],f[i&1^1][j-s[i].sum]+s[i].s.size());
}
std::cout<<*f[n&1^1];
return 0;
}
::: ::::info[思考:应该按照什么方式排序?]{open} 代码中
bool operator < (const Node& other) const {
if(sum>0 ^ other.sum>0) return sum>0;
if(sum>0) return pre>other.pre;
return pre-sum<other.pre-other.sum;
}
是怎么得来的呢? :::success[答案 / 推导过程]
$sum$:价值(定义见题解部分) **注意**:为了方便展现,这里的 $pre>0$ 即代码中的 $pre=0$。
容易发现
-
若
pre\ge0 ,此时内部顺序无影响,只要保证它们都在最前面即可。 -
若
pre_x\cdot pre_y\le0 且pre_x+pre_y\neq0 ,只要把pre\ge0 的放前面即可。 -
否则此时
pre<0 ,考虑交换法。- 当
x 排在y 前时,两者都取需要满足前缀串价值v\ge -pre_x 且v+sum_x\ge -pre_y ,即v\ge\max\{-pre_x,-pre_y-sum_x\} - 当
y 排在x 前时,同理可得v\ge\max\{-pre_y,-pre_x-sum_y\}
若
x 排在y 前面更优,有\begin{align*}\max\{-pre_x,-pre_y-sum_x\}&<\max\{-pre_y,-pre_x-sum_y\}\\&\Downarrow\\\max\{pre_y,pre_x-sum_x\}&<\max\{pre_x,pre_y-sum_y\}\end{align*} 简单分讨
sum 的正负性可得:- 当
sum_x\cdot sum_y\le0 时,上式\Rightarrow sum_x>sum_y - 当
sum_x>0,\,sum_y>0 时,上式\Rightarrow pre_x>pre_y -
当 sum_x<0,\,sum_y<0 时,上式\Rightarrow pre_x-sum_x<pre_y-sum_y 但是注意该理论在实现时应满足 STL 比较函数的传递性和非自反性。而且直接按照理论实现过于复杂,可以直接把 pre<0 的情况推广到全局来实现。::::
- 当