Find a good division scheme with the smallest lexicographical order [greedy algorithm, summary]

Integer division - Niuke

Problem Description

The title requires us to find the partition scheme with the smallest lexicographical order among all good partitions for a given integer n . A good partition is a sequence of positive integers satisfying the following conditions:

  • The sum of all numbers in the sequence is equal to n
  • There are no identical numbers in the sequence

Solutions

We can use 贪心算法to solve this problem. We hope to find the division scheme with the smallest lexicographical order, so we can try to arrange the division numbers from small to large. The specific solution is as follows:

1. Define a variable sum to record the sum of numbers in the current division scheme.
2. Traverse from 1 to n, and add numbers to the division scheme in turn.
3. Every time a number i is added, add sum to i, and judge whether sum is greater than or equal to n - i

  • If sum is greater than or equal to n - i , it means that after adding the number i, the sum of the numbers in the division scheme is greater than or equal to n. Then we only need to output n - sum + i, which is the partition scheme with the smallest lexicographical order.
  • If the sum is less than n - i, we can continue to add the number i to the division scheme and output i.

4. Continue to loop until all numbers from 1 to n have been traversed.

AC code

#include<bits/stdc++.h>

using namespace std;

int main() {
    
    
    int t;
    cin >> t;
    
    while (t--) {
    
    
        int n;
        cin >> n;
        
        int sum = 0;
        for (int i = 1; i <= n; i++) {
    
    
            sum += i;
            
            if (sum >= n - i) {
    
    
                cout << n - sum + i << endl;
                break;
            } else {
    
    
                cout << i << " ";
            }
        }
    }
    
    return 0;
}

Question 1: Why does judging that sum is greater than or equal to n - i mean that all numbers have been found in the division scheme?
If sum + i is greater than or equal to n, then after adding the number i, the sum of the numbers in the division scheme is already greater than or equal to n, and there is no need to continue adding larger numbers. At this point, we only need to output n - sum + i, such a division scheme is the scheme with the smallest lexicographical order.

Guess you like

Origin blog.csdn.net/qq_22841387/article/details/131253490