Codevs (3657括弧序列 )

來源:互聯網
上載者:User

標籤:

題目連結:傳送門

題目大意:中文題,略

題目思路:區間DP

     這個題是問需要添加多少個括弧使之成為合法括弧序列,那麼我們可以先求有多少合法的括弧匹配,然後用字串長度減去匹配的括弧數就行

     狀態轉移方程主要是對於我們枚舉的區間 dp[i][j],如果 i 和 j 處的括弧能夠匹配,則dp[i][j]=dp[i+1][j-1]+1;

     因為我們是從小到大枚舉長度,所以小長度的區間一定是最優的,所以當 i 與 j 匹配時,則是子區間的最優值+1

#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <cstring>#include <stack>#include <cctype>#include <queue>#include <string>#include <vector>#include <set>#include <map>#include <climits>#define lson root<<1,l,mid#define rson root<<1|1,mid+1,r#define fi first#define se second#define ping(x,y) ((x-y)*(x-y))#define mst(x,y) memset(x,y,sizeof(x))#define mcp(x,y) memcpy(x,y,sizeof(y))using namespace std;#define gamma 0.5772156649015328606065120#define MOD 1000000007#define inf 0x3f3f3f3f#define N 100005#define maxn 1050typedef pair<int,int> PII;typedef long long LL;int n,m,cnt,temp,ans;char str[1000];int dp[105][105];int main(){    int i,j,group,Case=0;    while(scanf("%s",str+1)!=EOF){        mst(dp,0);        int len=strlen(str+1);        for(int p=2;p<=len;++p)        for(i=1;i<=len;++i){            j=i+p-1;if(j>len)break;            if((str[i]==‘(‘&&str[j]==‘)‘)||(str[i]==‘[‘&&str[j]==‘]‘))dp[i][j]=dp[i+1][j-1]+1;            for(int k=i;k<j;++k){                dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);            }        }        printf("%d\n",len-dp[1][len]*2);    }    return 0;}

 

Codevs (3657括弧序列 )

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.