Codeforces Round 690 (Div. 3) C. Unique Number

125 阅读2分钟

题目链接

题目详情

You are given a positive number xx. Find the smallest positive integer number that has the sum of digits equal to xx and all digits are distinct (unique).

Input

The first line contains a single positive integer tt (1≤t≤501≤t≤50) — the number of test cases in the test. Then tt test cases follow.

Each test case consists of a single integer number xx (1≤x≤501≤x≤50).

Output

Output tt answers to the test cases:

  • if a positive integer number with the sum of digits equal to xx and all digits are different exists, print the smallest such number;
  • otherwise print -1.

input

4
1
5
15
50

output

1
5
69
-1

题目大意及解题思路

大意:
给你一个正数xx。查找数字和等于xx且所有数字都不同(唯一)的最小正整数。输入第一行包含单个正整数tt(1≤t≤501≤t≤50)-测试中的测试用例数。接下来是tt测试用例。每个测试用例由一个整数xx(1≤x≤501≤x≤50)组成。OutputOutput tt回答测试用例:如果存在一个数字总和等于xx且所有数字都不同的正整数,则打印最小的数字;否则打印-1。
解题思路:
给我们一个数n,让我们用1-9之间的数来组合成一个数,这个数总和等于n,且这个数尽可能的小。对于这样的情况,我们可以采用贪心思想。让这个数尽可能小,那么就让1-9之间大的数尽量往后面位(低位)上放,小的数才能放到高位上,整个数就尽可能小了。所以我们从9,8,7...依次枚举即可。那么什么时候无解呢?可以发现当1-9全部用完后(123456789),就无解了,这时n等于45,那也就意味这,只要n大于45,输出-1即可!!!

AC代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        if (n > 45) cout << -1 << endl;
        else
        {
            string s;
            int q = 9;
            while (n > 0)
            {
                if (n >= q)
                {
                    s += q + '0';
                    n -= q;
                    q--;
                }
                else
                {
                    s += n + '0';
                    break;
                }
            }
            reverse(s.begin(), s.end());
            cout << s << endl;
        }
    }
    return 0;
}