zoukankan      html  css  js  c++  java
  • Codeforces 508E Arthur and Brackets 区间dp

    Arthur and Brackets

    区间dp, dp[ i ][ j ]表示第 i 个括号到第 j 个括号之间的所有括号能不能形成一个合法方案。

    然后dp就完事了。

    #include<bits/stdc++.h>
    #define LL long long
    #define fi first
    #define se second
    #define mk make_pair
    #define PLL pair<LL, LL>
    #define PLI pair<LL, int>
    #define PII pair<int, int>
    #define SZ(x) ((int)x.size())
    #define ull unsigned long long
    using namespace std;
    
    const int N = 600 + 7;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int mod = 1e9 + 7;
    const double eps = 1e-8;
    
    int f[N][N];
    int path[N][N];
    
    int n, L[N], R[N];
    char ans[N << 1];
    
    int dp(int i, int j) {
        if(i > j) return true;
        if(~f[i][j]) return f[i][j];
        if(i == j) return L[i] <= 1 && R[i] >= 1;
        f[i][j] = false;
        for(int k = i; k <= j; k++) {
            if(2 * (k - i) + 1 < L[i] || 2 * (k - i) + 1 > R[i]) continue;
            if(dp(i + 1, k) && dp(k + 1, j)) {
                f[i][j] = true;
                path[i][j] = k - i;
                break;
            }
        }
        return f[i][j];
    }
    
    void print(int i, int j, int start, int cnt) {
        if(i > j) return;
        ans[start] = '(';
        ans[start + cnt * 2 + 1] = ')';
        print(i + 1, i + cnt, start + 1, path[i + 1][i + cnt]);
        print(i + cnt + 1, j, start + 2 * cnt + 2, path[i + cnt + 1][j]);
    }
    
    int main() {
        memset(f, -1, sizeof(f));
        scanf("%d", &n);
        ans[2 * n + 1] = '';
        for(int i = 1; i <= n; i++) scanf("%d%d", &L[i], &R[i]);
        if(!dp(1, n)) puts("IMPOSSIBLE");
        else {
            print(1, n, 1, path[1][n]);
            puts(ans + 1);
        }
        return 0;
    }
    
    /*
    */

      

  • 相关阅读:
    1029: [JSOI2007]建筑抢修
    1028: [JSOI2007]麻将
    1050 棋盘染色 2
    1026: [SCOI2009]windy数
    1074: [SCOI2007]折纸origami
    839. Optimal Marks
    1024: [SCOI2009]生日快乐
    1025: [SCOI2009]游戏
    1023: [SHOI2008]cactus仙人掌图
    对前面的总结
  • 原文地址:https://www.cnblogs.com/CJLHY/p/10391579.html
Copyright © 2011-2022 走看看