Acdream 1417 Numbers(暴力枚举)

传送门
Numbers
Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others)
Submit Statistic Next Problem
Problem Description

  Consider numbers from 1 to n.
  You have to find the smallest lexicographically number among them which is divisible by k.

Input

  Input file contains several test cases. Each test case consists of two integer numbers n and k on a line(1 ≤ n ≤ 1018, 1 ≤ k ≤ n).
  The last test case is followed by a line that contains two zeroes. This line must not be processed.

Output

  For each test case output one integer number — the smallest lexicographically number not exceeding n which is divisible by k.

Sample Input

2000 17
2000 20
2000 22
0 0
Sample Output

1003
100
1012
Hint

多组数据
Source

Andrew Stankevich Contest 22

题目大意:
给你一个数 n(n<10^18),让你求字典序最小的不超过 n 的能够整除 k 的最小值
解题思路:
在这里需要注意一下是字典序也就是说1001比123小,其实我们可以枚举10^p(p<=18),那么最多也就是18位,我们把10^p以后第一个对k取模等于0的数用数字组记录下来(注意枚举的时候不要超过n),最后的答案一定是在这里面,我们最后只需要将其转化为字符串进行字典序就行了。

My Code:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
char str[20][20];
string s[20];
LL a[20];
int main()
{
    LL n, k;
    while(cin>>n>>k)
    {
        if(!n && !k)
            break;
        int p = 0;
        LL tp = n;
        while(tp)
        {
            p++;
            tp /= 10;
        }
        tp = 1;
        for(int i=0; i<p-1; i++)
            tp *= 10;
        int cnt = 0;
        LL tmp = tp%k;
        if(tmp)
            tmp = tp+k-tmp;
        else
            tmp = tp;
        if(tmp <= n)
            a[cnt++] = tmp;
        tp /= 10;
        while(tp)
        {
            tmp = tp%k;
            if(tmp)
                tmp = tp+k-tmp;
            else
                tmp = tp;
            if(tmp < tp*10)
                a[cnt++] = tmp;
            tp /= 10;
        }
        for(int i=0; i<cnt; i++)
        {
            int sum = 0;
            while(a[i])
            {
                int tp = a[i]%10;
                str[i][sum++] = tp+'0';
                a[i] /= 10;
            }
            str[i][sum] = '\0';
        }
        for(int i=0; i<cnt; i++)
        {
            int len = strlen(str[i]);
            ///cout<<str[i]<<endl;
            for(int j=0; j<len/2; j++)
            {
                char ch = str[i][len-j-1];
                str[i][len-j-1] = str[i][j];
                str[i][j] = ch;
            }
        }
        for(int i=0; i<cnt; i++)
            s[i] = str[i];
        sort(s, s+cnt);
        cout<<s[0]<<endl;
    }
    return 0;
}

你可能感兴趣的:(枚举)