zoukankan      html  css  js  c++  java
  • 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 + 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
    ", ans);
        }
        return 0;
    }
  • 相关阅读:
    【排序】题解_P1093奖学金
    简单了解连接服务器的要求
    centos7安装(纯文字版)
    JAVA虚拟机
    集合
    IO流
    反射
    多线程
    JAVA基础
    博客园皮肤文档
  • 原文地址:https://www.cnblogs.com/fenice/p/5572072.html
Copyright © 2011-2022 走看看