[HIHO1300]展胜地的鲤鱼旗(栈,dp)

时间:2023-03-08 18:00:11
[HIHO1300]展胜地的鲤鱼旗(栈,dp)

题目链接:http://hihocoder.com/problemset/problem/1300

给一个字符串,只包含'('和')',问存在多少个子串似的括号是匹配的。

匹配规则在题干中描(蒻)述(语)得(文)非常烂!

维护一个栈,栈中保存'('的下标。当遇到')'并且栈非空的时候,说明已经匹配到一对括号。取出栈顶'('的位置idx。并且记录此时状态,dp(i)=dp(idx-1)+1。

 #include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath> using namespace std; //kirai maxn
const int maxn = ;
int n;
int st[maxn], top;
int dp[maxn];
char str[maxn]; int main() {
// freopen("in", "r", stdin);
while(~scanf("%s", str)) {
top = ;
n = strlen(str);
memset(dp, , sizeof(dp));
for(int i = ; i < n; i++) {
if(str[i] == '(') st[top++] = i;
else {
if(top > ) {
int idx = st[--top];
dp[i] = + dp[idx-];
}
}
}
int ans = ;
for(int i = ; i < n; i++) {
printf("%d ", dp[i]);
ans += dp[i];
}
printf("%d\n", ans);
}
return ;
}