題目鏈接:點擊查看
題目大意:給出一個數位長度為偶數的數字 n,需要求出一個比 n 小的,且所有數位重新排列后可以形成回文串,要求這個數字盡可能大
題目分析:從最低位開始貪心,依次枚舉每一位的數字,然后貪心去給低位重新分配以及補充即可,因為題目保證了數位的長度為偶數,所以此題中回文串的條件只是單純約束了所有數位出現次數為偶數即可,不可能為奇數
唯一需要注意的就是對于最高位的取值范圍內不能出現 0,因為不允許有前導零
代碼:
?
//#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>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;char s[N];int cnt[10];int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.ans.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(cnt,0,sizeof(cnt));for(int i=1;i<=n;i++)cnt[s[i]-'0']++;for(int i=n;i>=1;i--){cnt[s[i]-'0']--;int limit=i==1?1:0;//不能有前導零 for(int j=s[i]-'0'-1;j>=limit;j--){cnt[j]++;vector<int>node;for(int k=9;k>=0;k--)if(cnt[k]&1)node.push_back(k);if(node.size()<=n-i){for(int k=1;k<i;k++)putchar(s[k]);printf("%d",j);for(int k=1;k<=n-i-node.size();k++)putchar('9');for(auto it:node)printf("%d",it);puts("");goto end;}cnt[j]--;}}for(int i=0;i<n-2;i++)putchar('9');puts("");end:;}return 0;
}
?
總結
以上是生活随笔為你收集整理的CodeForces - 946E Largest Beautiful Number(贪心+模拟)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。