hihocoder #1300 : 展胜地的鲤鱼旗 dp

时间:2023-03-09 09:26:15
hihocoder #1300 : 展胜地的鲤鱼旗 dp

题目链接:

http://hihocoder.com/problemset/problem/1300

题解:

先用栈预处理出每个‘)’匹配的‘(’的位子,放在pos数组中。

dp[i]表示以i结尾的合法子串个数,则易知转移方程:

dp[i]=dp[pos[i]-1]+1;

代码:

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std; typedef long long LL;
const int maxn = 1e6 + ; char str[maxn];
LL dp[maxn];
int pos[maxn]; void init() {
memset(pos, , sizeof(pos));
memset(dp, , sizeof(dp));
} int main() {
while (scanf("%s", str + ) == ) {
int len = strlen(str + );
init();
stack<int> ms;
for (int i = ; i <= len; i++) {
if (str[i] == '(') {
ms.push(i);
}
else {
if (!ms.empty()) {
int j = ms.top(); ms.pop();
pos[i] = j;
}
}
}
LL ans = ;
for (int i = ; i <= len; i++) {
if(pos[i]>=) dp[i] = dp[pos[i] - ] + ;
ans += dp[i];
}
printf("%lld\n", ans);
}
return ;
}