Codeforces Round #343 (Div. 2) (C. Famil Door and Brackets(DP))

來源:互聯網
上載者:User

標籤:

題目連結:點擊開啟連結

題意:給你一個長度為m的只含()的括弧串s, 要求在s兩端在加兩個串p和q, 使得總長度為n,並且平衡, 平衡是指任意首碼串的(都不少於), 並且整個串的(和)一樣多。

思路:我們不難想到這樣一個DP, d[i][j]表示長度為i的串,(比)多j個(或者)比(多j個, 是等價的)的方案數。  那麼轉移很簡單:

if(j > 0) d[i][j] += d[i-1][j-1] ;    d[i][j] += d[i-1][j+1]。

然後為了滿足那兩個條件, 我們計算出s串的最小平衡度minx,以及s整個串的平衡度cur,枚舉第一個串的長度和平衡度, 那麼我們就可以算出第二個串的長度和平衡度, 這樣就可以累加答案了。 

細節參見代碼:

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<string>#include<vector>#include<stack>#include<bitset>#include<cstdlib>#include<cmath>#include<set>#include<list>#include<deque>#include<map>#include<queue>#define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;typedef long double ld;const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;const int mod = 1000000000 + 7;const int INF = int(1e9);const ll INF64 = ll(1e18);const int maxn = 2000 + 10;int T,n,m;ll d[maxn][maxn];void add(ll &a, ll b) {    a += b;    if(a >= mod) a -= mod;}char s[(int)(1e5 + 10)];int main() {    scanf("%d%d",&n,&m);    scanf("%s",s+1);    memset(d, 0, sizeof(d));    d[0][0] = 1;    for(int i=1;i<=n-m;i++) {        for(int j=0;j<=i;j++) {            if(j > 0) {                add(d[i][j], d[i-1][j-1]);            }            add(d[i][j], d[i-1][j+1]);        }    }    int minx = INF;    int cur = 0;    for(int i=1;i<=m;i++) {        if(s[i] == '(') ++cur;        else --cur;        minx = min(minx, cur);    }    ll ans = 0;    for(int i=0;i<=n-m;i++) {        for(int j=0;j<=i;j++) {            if(j + minx >= 0 && j + cur <= n-m-i) {                add(ans, d[i][j] * d[n-m-i][j+cur] % mod);            }        }    }    printf("%I64d\n",ans);    return 0;}


Codeforces Round #343 (Div. 2) (C. Famil Door and Brackets(DP))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.