435B - Pasha Maximizes - CodeForces Solution


greedy *1400

Please click on ads to support us..

Python Code:

s, k = input().split()
s = list(s)
k = int(k)
n = len(s)


def find_best_move(start):
    best_move = s[start]
    best_move_index = None
    for i in range(start, min(start + k + 1, n)):
        if s[i] > best_move:
            best_move = s[i]
            best_move_index = i
    return best_move_index


def swap(i, j):
    for index in range(j, i, -1):
        c = s[index]
        s[index] = s[index - 1]
        s[index - 1] = c


for i in range(n):
    pos = find_best_move(i)
    if not pos:
        continue
    nb_swap = pos - i
    if pos and nb_swap <= k:
        swap(i, pos)
        k = k - nb_swap


print(''.join(s))

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{ int a,k;
  cin>>a>>k;
  vector<int>digits;
  while(a)
  { digits.push_back(a%10);
    a/=10;
  }
  reverse(digits.begin(),digits.end());
  int n=digits.size();
  while(k)
  { bool flag=false;
    for(int i=0;i<digits.size()-1;i++)
    { if(digits[i]!=9)
      { int index=-1;
        int maxi=digits[i];
        for(int j=i+1;j<=min(i+k,n-1);j++)
        { if(digits[j]>maxi)
          { maxi=digits[j];
            index=j;
          }
        }
        if(index!=-1)
        { k-=(index-i);
          int temp=digits[index];
          for(int j=index;j>=i+1;j--)
          digits[j]=digits[j-1];
          digits[i]=temp;
          flag=true;
          break;
        }
      }
    }
    if(flag==false)
    break;
  }
  string ans="";
  for(int i=0;i<n;i++)
  ans+=(digits[i]+'0');
  cout<<ans;
  return 0;
}


Comments

Submit
0 Comments
More Questions

868A - Bark to Unlock
873B - Balanced Substring
1401D - Maximum Distributed Tree
1716C - Robot in a Hallway
1688B - Patchouli's Magical Talisman
99A - Help Far Away Kingdom
622B - The Time
1688C - Manipulating History
1169D - Good Triple
1675B - Make It Increasing
588A - Duff and Meat
1541B - Pleasant Pairs
1626B - Minor Reduction
1680A - Minimums and Maximums
1713A - Traveling Salesman Problem
1713B - Optimal Reduction
1710A - Color the Picture
1686B - Odd Subarrays
251A - Points on Line
427C - Checkposts
1159A - A pile of stones
508A - Pasha and Pixels
912A - Tricky Alchemy
1249A - Yet Another Dividing into Teams
1713C - Build Permutation
1699A - The Third Three Number Problem
1617B - GCD Problem
841A - Generous Kefa
1690B - Array Decrements
1692C - Where's the Bishop