博客
关于我
【题解】括号树
阅读量:187 次
发布时间:2019-02-28

本文共 1025 字,大约阅读时间需要 3 分钟。

在这里插入图片描述

solution:

本题是个树上问题,但我们不妨从线性状态上去考虑。这题就是一道区间dp了。

问题:给定字符串S,求有多少合法括号子串?

()()(())

f [ i ] f[i] f[i]表示前 i i i个的合法子串个数, g [ i ] g[i] g[i]表示以 i i i结尾的合法字符串个数。

考虑如下转移:

g [ i ] = g [ k ] + 1 g[i]=g[k]+1 g[i]=g[k]+1

f [ i ] = f [ i − 1 ] + g [ i ] f[i]=f[i-1]+g[i] f[i]=f[i1]+g[i]

其中 [ k + 1 , i ] [k+1,i] [k+1,i]为合法子串。

例如,上图中, [ 5 , 8 ] [5,8] [5,8] ( ( ) ) (()) (())为合法子串,所以 g [ 8 ] = g [ 4 ] + 1 = 3 g[8]=g[4]+1=3 g[8]=g[4]+1=3 f [ 8 ] = f [ 7 ] + g [ 8 ] = 3 + 3 = 6 f[8]=f[7]+g[8]=3+3=6 f[8]=f[7]+g[8]=3+3=6

上述过程可以用栈模拟。时间复杂度是 O ( n ) O(n) O(n)

如何扩展到树上呢?我们知道, d f s dfs dfs是有回溯操作的,即一个分支结束后可以回到原始状态。这就很巧妙了,我们只需要用一个栈模拟回溯操作就行了。这样就得到了点到根的原括号序列 S S S O ( 1 ) O(1) O(1)转移,时间复杂度 O ( n ) O(n) O(n)

#include
#define int long longusing namespace std;const int N=5e5+5;char s[N];int n,fa[N],ans;int sta[N],Top,f[N],g[N];vector
son[N];void dfs(int x) { if(s[x]=='(') { sta[++Top]=x; f[x]=f[fa[x]]; g[x]=0; for(int i=0;i
0){ int t=sta[Top--]; g[x]=g[fa[t]]+1; f[x]=f[fa[x]]+g[x]; for(int i=0;i

转载地址:http://down.baihongyu.com/

你可能感兴趣的文章
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>