单调队列 / 单调栈
题意
给定一个字符串,选出一些字符形成新的字符串,使每个字符均只出现一次,要使新字符串字典序尽可能大,求该字符串
分析
- 要选出字典序最大的字符串,则字符最大的应尽可能靠前
- 用单调队列使字符大的占据靠前位置
- 若当前字符在队列中显然不能再出现,直接跳过
若需弹出的字符后序不再出现,显然不能弹出
Code
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;
const int mod=998244353;
const long long inf=1e18;
const int base=131;
const double pi=3.1415926;
#define ll long long
#define int long long
#define ull unsigned long long
#define maxx(a,b) (a>b?a:b)
#define minx(a,b) (a<b?a:b)
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug(...) fprintf(stderr, __VA_ARGS__)
inline ll qpow(ll base, ll n) { assert(n >= 0); ll res = 1; while (n) { if (n & 1) res = res * base % mod; base = base * base % mod; n >>= 1; } return res; }
ll gcd(ll a,ll b) {return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b) { return a*b/gcd(a,b); }
ll inv(ll a) {return a == 1 ? 1 : (ll)(mod - mod / a) * inv(mod % a) % mod;}
ll C(ll n,ll m){if (m>n) return 0;ll ans = 1;for (int i = 1; i <= m; ++i) ans=ans*inv(i)%mod*(n-i+1)%mod;return ans%mod;}
ll A(ll n,ll m){ll sum=1; for(int i=n;i>=n-m+1;i--) sum=(sum*i)%mod; return sum%mod;}
ll GetSum(ll L, ll R) {return (R - L + 1ll) * (L + R) / 2ll;} //等差数列求和
/************/
int t,n,cnt[505],vis[505];
string a;
deque<char> q;
signed main()
{
IOS;
cin>>t;
while(t--){
memset(vis,0,sizeof(vis));
memset(cnt,0,sizeof(cnt));
cin>>a;
n=a.length();
for(int i=0;i<n;i++){
cnt[a[i]]++;
}
for(int i=0;i<n;i++){
if(vis[a[i]]){
cnt[a[i]]--;
continue;
}
while(q.size()){
char back=q.back();
if(a[i]<back){
q.push_back(a[i]);
vis[a[i]]=1;
break;
}
if(cnt[back]>1){
cnt[back]--;
q.pop_back();
vis[back]=0;
}
else{
q.push_back(a[i]);
vis[a[i]]=1;
break;
}
}
if(q.empty()){
q.push_back(a[i]);
vis[a[i]]=1;
}
}
while(q.size()){
char c=q.front();
cout<<c;
q.pop_front();
}
cout<<endl;
}
return 0;
}