HDU 3351 Seinfeld(括弧匹配)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=3351

解題報告:輸入一個只有‘{‘跟‘}‘的字串,有兩種操作,一種是把‘{‘變成‘}‘,另一種是‘}‘變成‘{‘,問你要把這個字串的括弧變成合法的最少需要多少次操作。

在刷DP專題,居然有個這個題目,看起來也像是DP,一直在想用DP怎麼做,始終沒做出來,最後試下直接字串匹配居然A了。跟普通的字串匹配的區別就是

在插入‘}‘這個的時候判斷一下棧是不是為空白,如果棧為空白,則把這個‘}‘改為‘{‘再插入,最後判斷棧是不是空,如果棧不為空白,則剩下的一定都是‘{‘這個,所以只要把一般的

‘{‘這個改成‘}‘這個就可以了,所以還要加上一般的棧長度才是最後答案。

 1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 #include<deque> 6 using namespace std; 7 #define maxn 2005 8 char str[maxn]; 9 int dp[maxn][maxn];10 int judge(int i,int j)11 {12     int tot = 0;13     if(str[i] != ‘{‘) tot++;14     if(str[j] != ‘}‘) tot++;15     return tot;16 }17 deque<char> que;18 int main()19 {20 //    freopen("in.txt","r",stdin);21 //    freopen("out.txt","w",stdout);22     int kase = 1;23     while(scanf("%s",str)!=EOF)24     {25         int len = strlen(str),ans = 0;26         if(str[0] == ‘-‘) break;27         que.clear();28         for(int i = 0;i < len;++i)29         {30             if(str[i] == ‘{‘)31             que.push_front(str[i]);32             else33             {34                 if(que.empty())35                 {36                     que.push_front(‘{‘);37                     ans++;38                 }39                 else que.pop_front();40             }41         }42         if(!que.empty())43         ans += (que.size()/2);44         printf("%d. %d\n",kase++,ans);45     }46     return 0;47 }48 /*        memset(dp,0,sizeof(dp));49         for(int i = len-1;i >= 0;--i)50         for(int j = i + 1;j < len;j+=2)51         {52             dp[i][j] = 0x7fffffff;53             if(j == i + 1) dp[i][j] = judge(i,j);54             else55             {56                 dp[i][j] = min(dp[i+1][j-1]+judge(i,j),dp[i][j]);57                 if(j >= 2)58                 dp[i][j] = min(dp[i][j-2]+judge(j-1,j),dp[i][j]);59                 if(i+2 < len)60                 dp[i][j] = min(dp[i+2][j]+judge(i,i+1),dp[i][j]);61             }62         }63         printf("%d. %d\n",kase++,dp[0][len-1]);64     }65     return 0;66 }*/
View Code

 

聯繫我們

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