zoukankan      html  css  js  c++  java
  • ZOJ 1463 Brackets Sequence

    区间DP,刘汝佳黑书p113例题

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <cstdlib>
     4 #include <algorithm>
     5 
     6 using namespace std;
     7 
     8 const int MAXN = 210;
     9 const int INF = 1 << 30;
    10 
    11 char str[MAXN];
    12 int dp[MAXN][MAXN];
    13 int path[MAXN][MAXN];
    14 bool vis[MAXN][MAXN];
    15 int len;
    16 
    17 inline bool check( char a, char b )
    18 {
    19     return (a == '(' && b == ')') || ( a == '[' && b == ']' );
    20 }
    21 
    22 void PrintPath( int i, int j )
    23 {
    24     if ( i > j ) return;
    25     if ( i == j )
    26     {
    27         if ( str[i] == '[' || str[i] == ']' )
    28             printf( "[]" );
    29         else printf( "()" );
    30         return;
    31     }
    32     if ( path[i][j] == -1 )
    33     {
    34         putchar( str[i] );
    35         PrintPath( i + 1, j - 1 );
    36         putchar( str[j] );
    37     }
    38     else
    39     {
    40         PrintPath( i, path[i][j] );
    41         PrintPath( path[i][j] + 1, j );
    42     }
    43 }
    44 
    45 void DP()
    46 {
    47     for ( int i = 1; i <= len; ++i ) dp[i][i - 1] = 0;
    48     for ( int i = 1; i <= len; ++i ) dp[i][i] = 1;
    49 
    50     for ( int p = 1; p < len; ++p )
    51     for ( int i = 1; i <= len - p; ++i )
    52     {
    53         int j = i + p;
    54         dp[i][j] = INF;
    55         if ( check( str[i], str[j] ) )
    56         {
    57             if ( dp[i + 1][j - 1] < dp[i][j] )
    58             {
    59                 dp[i][j] = dp[i + 1][j - 1];
    60                 path[i][j] = -1;
    61             }
    62         }
    63 
    64         for ( int k = i; k < j; ++k )
    65         {
    66             if ( dp[i][k] + dp[k + 1][j] < dp[i][j] )
    67             {
    68                 dp[i][j] = dp[i][k] + dp[k + 1][j];
    69                 path[i][j] = k;
    70             }
    71         }
    72     }
    73     return;
    74 }
    75 
    76 int main()
    77 {
    78     int T;
    79     bool flag = false;
    80     scanf( "%d", &T );
    81     getchar();
    82     while ( T-- )
    83     {
    84         getchar();
    85         gets( &str[1] );
    86         len = strlen( &str[1] );
    87         DP();
    88         if ( flag ) putchar('\n');
    89         PrintPath( 1, len );
    90         putchar('\n');
    91         flag = true;
    92     }
    93     return 0;
    94 }
  • 相关阅读:
    iOS9TableView分割线默认不显示,只有滑动的时候才显示 解决办法
    bug调试大全
    清理缓存
    Objective-C文件和目录操作,IOS文件操作,NSFileManager使用文件操作
    dispatch_async 与 dispatch_get_global_queue 的使用方法
    ios UISearchController
    开发报错调试总结
    返回查询结果的id返回插入数据的id值
    前端监听事件
    datetime-local设置初始值
  • 原文地址:https://www.cnblogs.com/GBRgbr/p/3061429.html
Copyright © 2011-2022 走看看