zoj 3829 Known Notation(貪心),zojnotation

來源:互聯網
上載者:User

zoj 3829 Known Notation(貪心),zojnotation

題目連結:zoj 3829 Known Notation

題目大意:給定一個不完整的尾碼運算式,要求有2種不同操作,用盡量少的操作使得運算式完整。

解題思路:貪心,數位個數要要保證比∗的個數多1,不夠的話優先補在開頭是最優的。然後遍曆一遍字串,碰到數字+1,碰到∗-1,保證數位個數大於等1,如果不夠減的話,可以和最後面的一個數字交換位置(用棧維護十分方便),因為添加和交換代價都是1。
不過這題資料實在夠弱的,因為11∗1這種情況,至少需要添加一個∗號才可以(特判即可),但是居然也可以過,同步賽的時候因為考慮了這個還WA了一次,因為11的情況還是為0的。

#include <cstdio>#include <cstring>#include <stack>#include <algorithm>using namespace std;const int maxn = 1005;char s[maxn];int solve () {    stack<int> sta;    int len = strlen(s), c = 0;    for (int i = 0; i < len; i++) {        if (s[i] == '*')            c++;        else            sta.push(i);    }    if (c == 0)        return 0;    int n = len - c;    int ret = n = max(c + 1 - n, 0);    for (int i = 0; i < len; i++) {        if (s[i] == '*') {            if (n <= 1) {                s[sta.top()] = '*';                sta.pop();                n++;                ret++;            } else                n--;        } else             n++;    }    if (ret == 0 && s[len-1] != '*')        ret++;    return ret;}int main () {    int cas;    scanf("%d", &cas);    while (cas--) {        scanf("%s", s);        printf("%d\n", solve());    }    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.