Codeforces Round #584 C. Paint the Digits

链接:

https://codeforces.com/contest/1209/problem/C

题意:

You are given a sequence of n digits d1d2…dn. You need to paint all the digits in two colors so that:

each digit is painted either in the color 1 or in the color 2;
if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color 2, then the resulting sequence of n digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit).
For example, for the sequence d=914 the only valid coloring is 211 (paint in the color 1 two last digits, paint in the color 2 the first digit). But 122 is not a valid coloring (9 concatenated with 14 is not a non-decreasing sequence).

It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.

Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.

思路:

枚举x, 比x小的为1,比x大的为2, 同时对x分类, 考虑将右边第一位比x小的右边的x放到1,其余的放到2.
检查一下.

代码:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5+10;

char s[MAXN];
int Col[MAXN];
int n;

bool Check()
{
    int mmin = 0;
    for (int i = 1;i <= n;i++)
    {
        if (Col[i] == 2)
            continue;
        if (s[i] < mmin)
            return false;
        mmin = s[i];
    }
    mmin = 0;
    for (int i = 1;i <= n;i++)
    {
        if (Col[i] == 1)
            continue;
        if (s[i] < mmin)
            return false;
        mmin = s[i];
    }
    return true;
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        set<int> St;
        scanf("%d", &n);
        scanf("%s", s+1);
        bool ok = false;
        for (int i = 0;i <= 9;i++)
        {
            for (int j = 1;j <= n;j++)
            {
                if (s[j]-'0' < i)
                    Col[j] = 1;
                else if (s[j]-'0' > i)
                    Col[j] = 2;
            }
            bool flag = true;
            for (int j = n;j >= 1;j--)
            {
                if (s[j]-'0' < i)
                    flag = false;
                if (s[j]-'0' != i)
                    continue;
                if (!flag)
                    Col[j] = 2;
                else
                    Col[j] = 1;
            }
            if (Check())
            {
                ok = true;
                break;
            }
        }
        if (!ok)
            puts("-");
        else
        {
            for (int i = 1;i <= n;i++)
                printf("%d", Col[i]);
            printf("\n");
        }
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/YDDDD/p/11645368.html