sgu 179 分类: sgu 2015-03-11 21:25 32人阅读 评论(0) 收藏


感谢Owaski的帮助


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>

const int MAXN = 10005;

char s[MAXN] = {'\0'};int n;
int fc[256] = {0}, sum[MAXN] = {0};

void fold(int l ,int r , int p)
{
    int sum = r - l + 1;
    int t = (sum - p)>>1;

    for(int i = l; i < l + t ; i++) s[i] = '(';
    for(int i = l + t; i <= r ; i++) s[i] = ')';

}

bool solve()
{
    int i;

    if(s[n - 1] == '(')
    {    
        for(i = n - 1; i > 1 ; i--)
          if(s[i - 1] == '(' && s[i] == ')')
            {
              s[i - 1] = ')', s[i] = '(';   

              if(sum[i - 2] > 0)
              {
                 fold(i , n , sum[i-2] - 1);
                 return true;
              }
            }

        return false;
    }
    else
    {
      for(i = n - 2; i > 0 ; i--)
         if(s[i] == '(')
         {
            s[i] = ')',s[i+1] = '(';
            break;
         }
      return true;
    }

}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("sgu179.in","r",stdin);
    freopen("sgu179.out","w",stdout);
#endif    

    scanf("%s",s+1);
    fc['('] = 1, fc[')'] = -1;

    n = strlen(s+1);

    for(int i = 1 ; i <= n ;i++)
      sum[i] = sum[i-1] + fc[s[i]]; 

    if(solve()==true)
        puts(s+1);
    else 
        puts("No solution");

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif      
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-03-11 21:25  <Dash>  阅读(140)  评论(0编辑  收藏  举报