當前位置:
首頁 >
CodeForces - 1506G Maximize the Remaining String(单调栈+贪心)
發布時間:2024/4/11
42
豆豆
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1506G Maximize the Remaining String(单调栈+贪心)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個長度為 nnn 的字符串,假設共出現了 kkk 種字母,現在要求出一個長度為 kkk 的子序列,滿足每種字母只出現一次,且字典序最大
題目分析:和之前牛客上的一道題目模型一樣,都是借助單調棧實現的貪心,考慮用單調棧維護答案序列,現在新加入了一個字母 chchch,分情況討論:
模擬整個過程,最后將棧中的答案序列倒過來輸出就好了
代碼:
// Problem: G. Maximize the Remaining String // Contest: Codeforces - Codeforces Round #710 (Div. 3) // URL: https://codeforces.com/contest/1506/problem/G // Memory Limit: 256 MB // Time Limit: 2500 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; char s[N]; int last[30]; bool vis[30]; int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--) {scanf("%s",s+1);int n=strlen(s+1);memset(last,-1,sizeof(last));memset(vis,false,sizeof(vis));for(int i=1;i<=n;i++) {last[s[i]-'a']=i;}stack<char>st;for(int i=1;i<=n;i++) {if(vis[s[i]-'a']) {continue;}while(!st.empty()&&st.top()<s[i]&&last[st.top()-'a']>i) {vis[st.top()-'a']=false;st.pop();}st.push(s[i]);vis[s[i]-'a']=true;}string ans;while(!st.empty()) {ans+=st.top();st.pop();}reverse(ans.begin(),ans.end());cout<<ans<<endl;}return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1506G Maximize the Remaining String(单调栈+贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1498E T
- 下一篇: CodeForces - 1484D P