1759F - All Possible Digits - CodeForces Solution


binary search data structures greedy math number theory *1800

Please click on ads to support us..

C++ Code:

#include <iostream>
#include <vector>
#include <unordered_set>
#define sz(x) int(x.size())
using namespace std;


int main() {
    int t;
    cin >> t;

    while (t--) {
        int n, p;
        cin >> n >> p;
        vector<int> digits;
        unordered_set<int> board;
        while (n--) {
            int num;
            cin >> num;
            digits.push_back(num);
            board.insert(num);
        }
        int last_digit = digits[sz(digits) - 1];
        int closest_left = last_digit;
        int operations = 0;
        while(board.find(closest_left) != board.end() && closest_left >= 0)
            closest_left--;
        if(closest_left >= 0){
            operations += p - last_digit;
            for(int i = sz(digits) - 2; i >= 0; i--){
                if(digits[i] != p - 1) {
                    board.insert(digits[i] + 1);
                    break;
                }
                if(i == 0)
                    board.insert(1);
            }
            if(sz(digits) == 1)
                board.insert(1);
            board.insert(0);
            closest_left = last_digit;
            while(board.find(closest_left) != board.end() && closest_left > 0)
                closest_left--;
            operations += closest_left;
        } else {
            int last = p - 1;
            while(board.find(last) != board.end() && last != last_digit)
                last--;
            operations = last - last_digit;
        }

    cout << operations << endl;

    }

    return 0;
}





Comments

Submit
0 Comments
More Questions

1613A - Long Comparison
1624B - Make AP
660B - Seating On Bus
405A - Gravity Flip
499B - Lecture
709A - Juicer
1358C - Celex Update
1466B - Last minute enhancements
450B - Jzzhu and Sequences
1582C - Grandma Capa Knits a Scarf
492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse
1654C - Alice and the Cake
369A - Valera and Plates
1626A - Equidistant Letters
977D - Divide by three multiply by two
1654B - Prefix Removals
1654A - Maximum Cake Tastiness
1649A - Game
139A - Petr and Book
1612A - Distance
520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class