1730C - Minimum Notation - CodeForces Solution


data structures greedy math sortings

Please click on ads to support us..

Python Code:

import os
import sys
import math
from io import BytesIO, IOBase
from collections import deque,defaultdict,OrderedDict,Counter
from heapq import heappush,heappop,heapify
from bisect import bisect_right,insort,bisect_left
from functools import lru_cache
from itertools import permutations,combinations

sys.setrecursionlimit(10**6)

def STRIN():return input()
def INTIN():return int(input())
def LINT():return list(map(int,input().split()))
def LSTR():return list(map(str,input().split()))
def MINT():return map(int,input().split())
def MSTR():return map(str,input().split())

def divisors(n) :
     
    c=0
    i=1
    while i <= int(math.sqrt(n)):
         
        if (n % i == 0) :
            if (n // i == i):
                c+=1
            else :
                c+=2
                 
        i = i + 1

    return c 

def isValid(x,y,n,m,graph,vis):
    if x<0 or x>=n or y<0 or y>=m or graph[x][y]=='#' or vis[x][y]:

        return False

    return True


def dfs(u,graph,vis,parent,p,vertex):
    
    vis[u]=1
   
    parent[u]=p
    for v in graph[u]:
       
        if vis[v]:
            if p!=v:
                vertex[0]=v 
                vertex[1]=u
                return True
 
        if not vis[v]:
            
            if dfs(v,graph,vis,parent,u,vertex):                               
                return True
    
    return False
 

def bfs(u,graph,vis,teams):
    pass

    
def palin(s):
    s=str(s)

    i=0
    j=len(s)-1

    while i<=j:
        if s[i]!=s[j]:
            return False

        i+=1
        j-=1


    return True




def solve():
    
    s=STRIN()
    s=list(s)
    ans=[0]*len(s)
    dic=defaultdict(list)

    for i,j in enumerate(s):
        dic[j].append(i)

    
    for j,i in enumerate(s):

        temp=int(i)
        temp-=1
        
        while temp>=0:
            
            if str(temp) in dic:
                l=dic[str(temp)]
                x=bisect_right(l,j)
                
                if x<len(l):
                    
                    s[j]=str(min(int(i)+1,9))

                    break

            temp-=1


    print(''.join(sorted(s)))




    











    

    
    
def main():
    ans=[]
    letter='abcdefghijklmnopqrstuvwxyz'
    
    for i in letter:
        ans.append(i)

    for i in letter:
        for j in letter:
            ans.append(i + j)
            
    for i in letter:
        for j in letter:
            for k in letter:
                ans.append(i + j + k)

    ans={}
    k=1
    for i in range(97,124):
        ans[str(k)]=chr(i)
        k+=1

    for _ in range(INTIN()):
        solve()
    
    
        






BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")


if __name__ == "__main__":
    main()

C++ Code:

#include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define ll long long int
#define fn(i ,st, n) for(int i = st; i < n; i++)
//typedef tree<pair<ll, ll>, null_type, less<pair<ll, ll>>, rb_tree_tag, tree_order_statistics_node_update > pbds;
ll gcd(ll a, ll b){if(b == 0) return a; return gcd(b, a % b);}
ll lcm(ll a, ll b){ return (a*b)/gcd(a,b);}
ll _power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}
ll _power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1;a *= a; a %= mod;} return p % mod;}
ll _modI(ll a, ll m){ return _power(a, m - 2, m);}
bool is_prime( ll n){if(n==1)return false; ll i=2;for(i=2;i*i<=n;i++){if(n%i==0){return false;}}return true;}
// Euler's totient function: Complexity-> O(sqrt(n))
ll ETF(ll n) {
    ll result = n;
    for (ll i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            while (n % i == 0)
                n /= i;
            result -= result / i;
        }
    }
    if (n > 1)
        result -= result / n;
    return result;
}

// Euler's value for 1 to n: Complexity-> O(nloglogn)
void nETF(ll n) {
    vector<ll> phi(n + 1);
    for (ll i = 0; i <= n; i++)
        phi[i] = i;

    for (ll i = 2; i <= n; i++) {
        if (phi[i] == i) {
            for (ll j = i; j <= n; j += i)
                phi[j] -= phi[j] / i;
        }
    }
}

const ll N = 2e5 + 5;
const ll sz = 1e6 + 5;
const ll mod = 1e9+7;
const ll inf = 1e18;

ll sum (vector<ll> &a, ll st, ll ed) {
    ll ret = 0;
    fn(i,st, ed) {
        ret += a[i];
    }

    return ret;
}

void solve(int tc)
{
    string s;
    cin >> s;

    ll n = s.length();
    int mn = s[n-1]-'0';
    for(int i=n-2; i>=0; i--) {
        int x = s[i] - '0';
        mn = min(mn, x);
        if(x > mn) x++;
        x = min(x, 9);
        s[i] = x+'0';
    }
    sort(s.begin(), s.end());
    cout << s << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    int t = 1;
    cin >> t;
    for(int i=1;i<=t;i++)
    {
        solve(i);
    }
}


Comments

Submit
0 Comments
More Questions

1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle
118A - String Task
236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments