HDU 4915 Parenthese sequence

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   資料   for   

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

解題報告:從前往後遍曆一次,每次判斷‘)‘的數目是不是滿足 n < (i +1)/ 2,從後往前遍曆一次,每次判斷‘(‘的數目是不是滿足 n <= (len - i) / 2;

這樣就可以判斷出這個序列是否存在匹配的序列。接下來就是判斷是Many還是Unique的情況,因為資料是10的六次方,所以遇到問號改成‘(‘ 或‘)‘暴力判斷是不行的,但是我們可以判斷出只要(和)的數目小於等於len / 2而且有三個連續的?那句是Many,否則再進行暴力判斷,這樣就可以大大減小時間複雜度。

 1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 const int maxn = 1000000+5; 7 char str[maxn]; 8  9 int judge(char* str)10 {11     int len = strlen(str);12     int a = 0,b = 0;13     for(int i = 0,j = len- 1;i < len,j >= 0;++i,--j)14     {15         if(str[i] == ‘)‘) a++;16         if(str[j] == ‘(‘) b++;17         if(a >  (i + 1) / 2) return 0;18         if(b > (len - j) / 2) return 0;19     }20     return 1;21 }22 int main()23 {24 //    freopen("1005.in","r",stdin);25     int T = 0;26     while(scanf("%s",str)!=EOF)27     {28         T++;29         int ans;30         ans = judge(str);31         int l = strlen(str);32         if(l & 1) ans = 0;33         if(!ans)34         {35             puts("None");36             continue;37         }38         int len =  strlen(str);39         int a = 0,b = 0,c = 0,f = 0,M = 0;40         for(int i = 0;i < len;++i)41         {42             if(str[i] == ‘(‘) a++;43             if(str[i] == ‘)‘) b++;44             if(str[i] == ‘?‘)45             {46                 f++;47                 c++;48             }49             else50             {51                 M = max(M,f);52                 f = 0;53             }54         }55         if(a >= len / 2 || b >= len / 2 || c <= 1)56         {57             puts("Unique");58             continue;59         }60         if(M >= 3)61         {62             puts("Many");63             continue;64         }65         ans = 0;66         for(int i = 0;i < len;++i)67         if(str[i] == ‘?‘)68         {69             int tt = 0;70             str[i] = ‘(‘;71             tt += judge(str);72             str[i] = ‘)‘;73             tt += judge(str);74             if(tt == 2)75             {76                 ans = 1;77                 break;78             }79             str[i] = ‘?‘;80         }81         printf(ans? "Many\n":"Unique\n");82     }83     return 0;84 }
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.