生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1422E Minlexes(dp+字符串)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:對一個長度為 n 的字符串 s 來說,可以進行的操作如下:
選出一個二元對 ( i , i + 1 )滿足 i >= 0 && i + 1 < ns[ i ] == s[ i + 1 ]可以將 s[ i ] 和 s[ i + 1 ] 一起刪除
現在給出一個字符串,要求對其 n 個后綴分別進行操作,使得操作后的字典序最小
題目分析:首先拋開題目,只看輸入輸出的話,題目對于輸出是有點小要求的,所以可以自己手寫一個結構體來滿足要求,算是一個小模擬,不多解釋了
又因為是對 n 個后綴進行操作,所以我們不妨從后向前來,這樣就能遍歷到每個后綴了
設 ans[ i ] 是第 i 個后綴經過操作后的字符串,不難看出 ans 數組是可以遞推的,因為上面說到了需要從后向前來,所以選擇倒著遞推,到了第 i 個位置時,分為三種情況討論一下:
如果 s[ i ] != s[ i + 1 ],ans[ i ] =??s[ i ] + ans[ i +?1 ]如果 s[ i ] == s[ i + 1 ] 如果刪除掉 s[ i ] 和 s[ i + 1 ] 更優,那么 ans[ i ] = ans[ i + 2 ]否則 ans[ i ] = s[ i ] + ans[ i + 1 ] = s[ i ] + s[ i ] + ans[ i + 2 ]
現在的問題轉換為,討論一下何時刪除掉 s[ i ] 和 s[ i + 1 ] 是更優的,感覺這里才是這個題目的難點:
s[ i ] < ans[ i + 2 ][ 0 ],顯然不刪是更優的s[ i ] > ans[ i + 2 ][ 0 ],顯然刪掉是更優的s[ i ] == ans[ i + 2 ][ 0 ],設 j 是滿足 ans[ i + 2 ][ j ] != ans[ i + 2 ][ 0 ] 的最小的下標 如果 ans[ i + 2 ][ 0 ] < ans[ i + 2 ][ j ],不刪是更優的否則刪掉是更優的
針對第三種情況簡單舉個例子,比如原字符串是 “123”,在前面加上一個 “1”,顯然 “1123” < “123”,另一種情況就是如果原字符串是 “321”,在前面加上一個 “3”,就得到了 “321” < “3321”
代碼:
?
//#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>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e5+100;struct Node
{string pref,suff;bool incr=false;int len=0;void push_front(char ch){if(!len)incr=false;else if(ch!=pref[0])incr=(ch<pref[0]);else{}len++;if(suff.size()<2)suff=ch+suff;pref=ch+pref;if(pref.size()>10)pref.pop_back();}
}ans[N];string s;int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endifios::sync_with_stdio(false); cin>>s;for(int i=s.size()-1;i>=0;i--){char ch=s[i];if(i+1<s.size()&&s[i]==s[i+1])//可以選擇刪除{ans[i]=ans[i+2];if(ans[i].len!=0&&(ch<ans[i].pref[0]||ch==ans[i].pref[0]&&ans[i].incr))//不刪更優 {ans[i].push_front(ch);ans[i].push_front(ch);}}else//無法選擇 {ans[i]=ans[i+1];ans[i].push_front(ch);}}for(int i=0;i<s.size();i++){if(ans[i].len<=10)cout<<ans[i].len<<' '<<ans[i].pref<<endl;elsecout<<ans[i].len<<' '<<ans[i].pref.substr(0,5)<<"..."<<ans[i].suff<<endl;}return 0;
}
?
總結
以上是生活随笔為你收集整理的CodeForces - 1422E Minlexes(dp+字符串)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。