hdu 4915 Parenthese sequence(高效)

來源:互聯網
上載者:User

標籤:style   http   color   os   io   for   ar   line   

題目連結:hdu 4915 Parenthese sequence

題目大意:給定一個序列,由(,),?組成?可以表示(或者),問說有一種、多種或者不存在匹配。

解題思路:從左向右,從右向左,分別維護左括弧和右括弧可能的情況,區間上下界。如果過程中出現矛盾,則為None,否則要判斷唯一解還是多解。枚舉每個問號的位置,假設該問號可為左右括弧,則有多解。

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1e6+5;char s[maxn];int n, l[maxn][2], r[maxn][2];bool check (int x) {    int ldown = l[x-1][0] + 1;    int lup = l[x-1][1] + 1;    if (ldown > r[x+1][1] || lup < r[x+1][0])        return false;    int rdown = r[x+1][0] + 1;    int rup = r[x+1][1] + 1;    if (rdown > l[x-1][1] || rup < l[x-1][0])        return false;    return true;}int judge () {    n = strlen(s+1);    if (n&1)        return 0;    memset(l[0], 0, sizeof(l[0]));    memset(r[n+1], 0, sizeof(r[n+1]));    for (int i = 1; i <= n; i++) {        if (s[i] == ‘(‘) {            l[i][0] = l[i-1][0] + 1;            l[i][1] = l[i-1][1] + 1;        } else if (s[i] == ‘)‘) {            if (l[i-1][1] == 0)                return 0;            l[i][0] = (l[i-1][0] == 0 ? l[i-1][0] + 2 : l[i-1][0]) - 1;            l[i][1] = l[i-1][1] - 1;        } else {            l[i][0] = (l[i-1][0] == 0 ? l[i-1][0] + 2 : l[i-1][0]) - 1;            l[i][1] = l[i-1][1] + 1;        }    }    for (int i = n; i; i--) {        if (s[i] == ‘)‘) {            r[i][0] = r[i+1][0] + 1;            r[i][1] = r[i+1][1] + 1;        } else if (s[i] == ‘(‘) {            if (r[i+1][1] == 0)                return 0;            r[i][0] = (r[i+1][0] == 0 ? r[i+1][0] + 2 : r[i+1][0]) - 1;            r[i][1] = r[i+1][1] - 1;        } else {            r[i][0] = (r[i+1][0] == 0 ? r[i+1][0] + 2 : r[i+1][0]) - 1;            r[i][1] = r[i+1][1] + 1;        }    }    for (int i = 1; i <= n; i++)        if (s[i] == ‘?‘ && check(i))            return 2;    return 1;}int main () {    while (scanf("%s", s+1) == 1) {        int flag = judge();        if (flag == 2)            printf("Many\n");        else if (flag == 1)            printf("Unique\n");        else            printf("None\n");    }    return 0;}

聯繫我們

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