hihocoder 展胜地的鲤鱼旗

来源:互联网 发布:靠谱的淘宝only代购店 编辑:程序博客网 时间:2024/04/28 05:43




题目:

点击打开链接

思路: 
以dp[i]表示以i结尾的符合题目子串的个数,则 i 对应的位置 只能是 ) , 那么以i结尾的该怎么算呢 ,就是以i 结尾对应左括号位置的前一个符号以它结尾的的个数+1 
例如:
()().().() 以第三个右括号结尾的有三个,那么以第四个右括号结尾的就有3+1

#include<stdio.h>#include<stack>#include<string.h>using namespace std;char a[1000010];long long dp[1000010];int main(){    scanf("%s",a+1);    int len = strlen(a+1);    stack<int>s;    long long ans = 0;    for(int i =1; i<=len; i++)    {        if(a[i]=='(')        {            s.push(i);            dp[i]= 0;        }        else        {            if(!s.empty())            {                int k = s.top();                s.pop();                dp[i]+= dp[k-1]+1;                ans+=dp[i];            }        }    } printf("%lld\n",ans);    return 0;}

0 0
原创粉丝点击