946E - Largest Beautiful Number - CodeForces Solution


greedy implementation *2200

Please click on ads to support us..

C++ Code:

// Hydro submission #[email protected]
#include<bits/stdc++.h>
using namespace std;

char s[200010];
int n;
int num[200010][10];

void solve(){
	for(int i=n;i>=1;i--){
		for(int j=s[i]-'1';j>=0;j--){
			if(i==1&&j==0) continue;
			int x=0;
			for(int k=0;k<10;k++) x+=num[i-1][k]^(k==j);
			if(x<=n-i){
				for(int k=1;k<i;k++) putchar(s[k]);
				putchar(j+'0');
				for(int k=i+1;k<=n-x;k++) putchar('9');
				for(int k=9;k>=0;k--){
					if(num[i-1][k]^(j==k)) putchar(k+'0');
				}
				puts("");
				return;
			}
		}
	}
	for(int i=1;i<=n-2;i++) putchar('9');
	puts("");
}


int main(){
	int t;cin>>t;
	while(t--){
		scanf("%s",s+1);
		n=strlen(s+1);
		for(int i=1;i<=n;i++){
			int ii=s[i]-'0';
			for(int k=0;k<10;k++){
				num[i][k]=num[i-1][k]^(ii==k);
			}
		}
		solve();
	}
	
	return 0;
}


Comments

Submit
0 Comments
More Questions

677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation
893C - Rumor
227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys