码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-06-09 11:01:08      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:

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 + 10;

char str[maxn];
LL dp[maxn];
int pos[maxn];

void init() {
    memset(pos, 0, sizeof(pos));
    memset(dp, 0, sizeof(dp));
}

int main() {
    while (scanf("%s", str + 1) == 1) {
        int len = strlen(str + 1);
        init();
        stack<int> ms;
        for (int i = 1; i <= len; i++) {
            if (str[i] == () {
                ms.push(i);
            }
            else {
                if (!ms.empty()) {
                    int j = ms.top(); ms.pop();
                    pos[i] = j;
                }
            }
        }
        LL ans = 0;
        for (int i = 1; i <= len; i++) {
            if(pos[i]>=1) dp[i] = dp[pos[i] - 1] + 1;
            ans += dp[i];
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

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

标签:

原文地址:http://www.cnblogs.com/fenice/p/5572072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!