/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 320.0 KiB
#3 Accepted 28ms 584.0 KiB
#4 Accepted 28ms 1.074 MiB
#5 Accepted 55ms 3.598 MiB
#6 Accepted 52ms 3.465 MiB
#7 Accepted 40ms 612.0 KiB
#8 Accepted 42ms 736.0 KiB
#9 Accepted 19ms 1.391 MiB
#10 Accepted 27ms 592.0 KiB
#11 Accepted 37ms 1.621 MiB

Code

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    int T;
    cin >> T;
    
    while(T--){
        long long N, K;
        cin >> N >> K;
        
        vector<long long> A(N);
        for(auto &x : A) cin >> x;
        
        // Sort the array to count frequencies efficiently
        sort(A.begin(), A.end());
        
        // Count frequencies
        vector<long long> freqs;
        if(N > 0){
            long long current = A[0];
            long long cnt = 1;
            for(int i = 1; i < N; i++){
                if(A[i] == current){
                    cnt++;
                }
                else{
                    freqs.push_back(cnt);
                    current = A[i];
                    cnt = 1;
                }
            }
            freqs.push_back(cnt); // Push the count of the last element
        }
        
        // Sort frequencies in descending order
        sort(freqs.begin(), freqs.end(), greater<long long>());
        
        // Determine group sizes
        long long Q = N / K;       // Base size of each group
        long long R = N % K;       // Number of groups that will have an extra element
        vector<long long> group_sizes;
        
        for(int i = 0; i < R; i++) group_sizes.push_back(Q + 1);
        for(int i = 0; i < K - R; i++) group_sizes.push_back(Q);
        
        // Sort group sizes in descending order
        sort(group_sizes.begin(), group_sizes.end(), greater<long long>());
        
        // Initialize max heap with frequencies
        priority_queue<long long> heap;
        for(auto c : freqs){
            heap.push(c);
        }
        
        long long coverage = 0;
        for(auto s : group_sizes){
            if(heap.empty()) break;
            long long c = heap.top();
            heap.pop();
            if(c >= s){
                coverage += s;
                if(c - s > 0){
                    heap.push(c - s);
                }
            }
            else{
                coverage += c;
                // No need to push back if c - s <= 0
            }
        }
        
        // The minimum number of changes is total elements minus the coverage
        long long minimal_changes = N - coverage;
        cout << minimal_changes << "\n";
    }
}

Information

Submit By
Type
Submission
Problem
P1062 Roy and Array
Language
C++17 (G++ 13.2.0)
Submit At
2024-10-05 02:30:18
Judged At
2024-11-11 02:40:55
Judged By
Score
100
Total Time
55ms
Peak Memory
3.598 MiB