CodeForces 490E Restoring Increasing Sequence(貪心),codeforces490e

來源:互聯網
上載者:User

CodeForces 490E Restoring Increasing Sequence(貪心),codeforces490e

CodeForces 490E Restoring Increasing Sequence(貪心)

CodeForces 490E

題目大意:給N個正整數,然而這些正整數中間有些數字是被‘?’遮擋住了,每個‘?’可以還原回一個數字,希望給定的這N個整數形成一個遞增的序列。可以的話,給出這N個整數的序列,不行返回N0.

解題思路:每個整數都在滿足條件的情況下盡量的小,寫了一個非遞迴版本的,發現要考慮的因素太多了,wa了太多遍。後面改成了遞迴版本的,但是這個比較耗時。

代碼:

#include <cstdio>#include <cstring>const int MAXL = 10;const int MAXN = 1e5 + 5;char str[MAXN][MAXL];int len[MAXN];int N;bool dfs (int i, int l1, int flag) {                if (l1 >= len[i]) {                 if (flag)            return true;        return false;    }    if (str[i][l1] != '?') {        if (!flag && str[i][l1] < str[i - 1][l1])            return false;        return dfs(i, l1 + 1, flag | str[i][l1] > str[i - 1][l1]);    } else {        if (flag) {            str[i][l1] = '0';            if (dfs(i, l1 + 1, flag))                return true;            str[i][l1] = '?';            return false;        }        for (char k = str[i - 1][l1]; k <= '9'; k++) {            str[i][l1] = k;            if (dfs(i, l1 + 1, k > str[i - 1][l1]))                return true;            }        str[i][l1] = '?';        return false;    }}bool judge(int i) {    if (len[i] < len[i - 1])        return false;    if (len[i] > len[i - 1]) {        if (str[i][0] == '?')            str[i][0] = '1';        for (int j = 1; j < len[i]; j++)            if (str[i][j] == '?')                str[i][j] = '0';        return true;    }    if (dfs(i, 0, 0))        return true;    return false;}bool handle () {    if (N == 1)        return true;    for (int i = 1; i < N; i++)         if (!judge(i))            return false;    return true;}void handle_first() {    int len = strlen(str[0]);    for (int i = 0; i < len; i++)        if (str[0][i] == '?')            str[0][i] = (i == 0) ?'1' : '0';}int main () {    while (scanf ("%d", &N) != EOF) {        for (int i = 0; i < N; i++) {            scanf ("%s", str[i]);            len[i] = strlen(str[i]);        }        handle_first();        if (handle()) {            printf ("YES\n");            for (int i = 0; i < N; i++)                  printf ("%s\n", str[i]);        } else            printf ("NO\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.