CodeForces - 1296E2 String Coloring (hard version) 思维+模拟

CodeForces - 1296E2 String Coloring (hard version)

原题地址:

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

题意:给你一个字符串,你可以对字符串的每一个字符染色,不同颜色的相邻字符之间可以相互交换;不计交换次数,问能够使得交换后字符串成字典序排序的最小使用颜色数,和对应的染色方法。

基本思路:可以发现,因为不同颜色的字符之间可以随意交换,所以只要保证相同颜色的字符是成字典序非严格递增排序就行了。
在实现上,只要遍历一遍字符串,用一个memo数组储存一下每个已使用颜色的字典序最大字符,对于每个遍历到的新字符,我们先判断该字符是否大于之前任意一个已使用颜色的最大字符,如果有则填该颜色并且更新memo,没有则新增一个颜色并且更新memo。

实现代码:

#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;
}
发布了23 篇原创文章 · 获赞 7 · 访问量 1756

猜你喜欢

转载自blog.csdn.net/weixin_44164153/article/details/104357725
今日推荐