E2. String Coloring (hard version)
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string ss consisting of nn lowercase Latin letters.
You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).
After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.
The goal is to make the string sorted, i.e. all characters should be in alphabetical order.
Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.
Input
The first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.
The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.
Output
In the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.
In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.
Examples
input
Copy
9 abacbecfd
output
Copy
2 1 1 2 1 2 1 2 1 2
input
Copy
8 aaabbcbb
output
Copy
2 1 2 1 2 1 2 1 1
input
Copy
7 abcdedc
output
Copy
3 1 1 1 1 1 2 3
input
Copy
5 abcde
output
Copy
1 1 1 1 1 1
可以想出其实本题就是请你找出
有多少个非递减子序列(最小)
很简单最多有26个 因为只有26个字母
我一开始的考虑是每次找最长非递减子序列 然后去掉 再找
最多找26次 但是我不会输出最长非递减子序列的元素
后来看了下别人的代码(发现贪心的考虑是多余的)
然后就很简单了
直接把每个元素放入能放的序列就好了(cf的tag太坑了)
#include <bits/stdc++.h>
using namespace std;
int now[30];
char s[200005];
int num[200005];
int main()
{
int n;
scanf("%d",&n);
scanf("%s",s+1);
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=30;j++)
{
if(s[i]>=now[j])
{
num[i]=j;
now[j]=s[i];
ans=max(ans,j);
break;
}
}
}
printf("%d\n",ans);
for(int i=1;i<=n;i++)
{
printf("%d ",num[i]);
}
printf("\n");
}