全部评论 1

  • #include <iostream>
    #include <vector>
    #include <queue>
    #include <algorithm>

    using namespace std;

    int main() {
    int T;
    cin >> T; // Read number of test cases
    while (T--) {
    int N, M;
    cin >> N >> M; // Read N and M
    vector<int> nums(N);
    for (int i = 0; i < N; ++i) {
    cin >> nums[i]; // Read N numbers
    }

        // Min-heap to store the largest M sums
        priority_queue<int, vector<int>, greater<int>> minHeap;
    
        // Calculate all unique sums and maintain the top M sums
        for (int i = 0; i < N; ++i) {
            for (int j = i + 1; j < N; ++j) {
                int sum = nums[i] + nums[j];
                minHeap.push(sum);
                if (minHeap.size() > M) {
                    minHeap.pop();  // Keep only the largest M sums
                }
            }
        }
    
        // Extract sums from the min-heap
        vector<int> largestSums;
        while (!minHeap.empty()) {
            largestSums.push_back(minHeap.top());
            minHeap.pop();
        }
    
        // Sort in descending order
        sort(largestSums.rbegin(), largestSums.rend());
    
        // Print the result
        for (int i = 0; i < largestSums.size(); ++i) {
            cout << largestSums[i];
            if (i < largestSums.size() - 1) cout << " ";  // Space between numbers
        }
        cout << endl;
    }
    
    return 0;
    

    }

    2024-08-27 来自 山东

    0
首页