Codeforces 1153 C Serval and Parenthesis Sequence
生活随笔
收集整理的這篇文章主要介紹了
Codeforces 1153 C Serval and Parenthesis Sequence
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
給一個字符串 只包含 ‘(’ 、 ‘)’ 、和 ’ ?’ 要求改變 ‘?’ 為 ‘(’ 或 ‘)’ 使最終的字符串滿足:從第一位開始到任意一位(非最后一位)的字符串不出現形如 ‘( )’的情況 如果沒有情況滿足 輸出 ’ : ) ’
思路:
貪心,當n為奇數或s的首字符為)或s的末尾字符為(時,必定不滿足題意;
也就是說s的首個字符必定是(且末尾字符必定是),那么對于1<=i<n的所有i,必須滿足[1,i]內的(的個數大于)的個數。
考慮用一個數先記錄下當前字符串中”(‘的個數,然后用n/2-當前的得到還需要轉化的。然后在進行遍歷轉化。
在轉化后通過遍歷字符串 統計 l 和 r 括號的數目 必須滿足 在最后一位之前必須有 l > r 且不可以相等 。來檢驗是否合法。
AC代碼:
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include<vector> #include<string> #include<queue> #include<map> #include<stack> #include<set> #include<ctime> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define max 2000int n;bool check(string ss,int & l,int & r) //檢驗最終的字符串是否合法 {bool is_true = true;for (int i = 0; i < n; i++){if (ss[i] == '(')++l;if (ss[i] == ')')++r;//因為"(" 個數與")"相同,且最后一個為")",那么在最后一個之前,"("個數必須大于")"if (l <= r && i != n - 1) {is_true = false;break;}}return is_true; }void show(string ss, bool is_true,int l,int r) {if (is_true){if (l == r)cout << ss << endl;elsecout << ":(" << endl;}elsecout << ":(" << endl; }int main() {string ss;while (cin >>n>> ss){if((n&1)|| ss[0] == ')' || ss[n - 1] == '(')cout << ":(" << endl;else{int count1 = 0;ss[0] = '(', ss[n - 1] = ')';for (int i = 0; i < n; i++){if (ss[i] == '(')++count1; //現在字符串中已經有的}//因為一半是“(”,s所以現在count1表示還需要轉化為“(”的個數count1 = n / 2 - count1; for (int i = 0; i < n; i++){if (ss[i] == '?' && count1){ss[i] = '(';--count1;}else if (ss[i] == '?')ss[i] = ')';}int l = 0, r = 0;bool is_true = check(ss,l,r);show(ss, is_true,l,r);}}return 0;} 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Codeforces 1153 C Serval and Parenthesis Sequence的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 已知gcd和lcm求a+b最小和?---
- 下一篇: P1080 国王游戏(贪心)