CodeForces-1296E2 String Coloring (hard version) Thinking + Simulation

CodeForces - 1296E2 String Coloring (hard version)

Original title address:

http://codeforces.com/problemset/problem/1296/E2

Topic: Give you a string, you can dye each character of the string, and adjacent characters of different colors can be exchanged with each other; regardless of the number of exchanges, ask the minimum use that can make the string lexicographically sorted after the exchange The number of colors, and the corresponding dyeing method.

Basic idea: It can be found that because characters of different colors can be exchanged at will, as long as the characters of the same color are in lexicographic order and not strictly ascending .
In the implementation, as long as it traverses the string once, use a memo array to store the largest lexicographic character of each used color. For each new character traversed, we first determine whether the character is greater than any of the used colors The largest character, if there is, fill in the color and update memo, if not, add a color and update memo.

Implementation code:

#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define INF 0x3f3f3f3f

const int maxn = 2e5 + 10;
int n;
string str;
int ans[maxn];
map<int,int> memo;
signed main() {
    IO;
    cin >> n;
    cin >> str;
    fill(ans, ans + n, -1);//储存答案;
    int num = 1;//当前使用的颜色数目;
    ans[0] = 1;
    memo[1] = str[0] - 'a';//先染色第一个字符;
    for (int i = 1; i < str.size(); i++) {
        int temp = str[i] - 'a';
        bool v = false;
        for (int j = 1; j <= num; j++) {//判断能否用之前的颜色染色该字符;
            if (temp >= memo[j]) {
                memo[j] = temp;
                ans[i] = j;
                v = true;
                break;
            }
        }
        if (!v) {//新增颜色并染色该字符;
            memo[++num] = temp;
            ans[i] = num;
        }
    }
    cout << num << endl;
    for (int i = 0; i < n; i++) cout << ans[i] << " ";
    cout << endl;
    return 0;
}
Published 23 original articles · won 7 · visited 1756

Guess you like

Origin blog.csdn.net/weixin_44164153/article/details/104357725
Recommended