CF219B:Special Offer! Super Price 999 Bourles!(贪心)

来源:互联网 发布:淘宝关注的店铺 哪里找 编辑:程序博客网 时间:2024/05/16 08:23

B. Special Offer! Super Price 999 Bourles!
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.

Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.

Polycarpus agrees to lower the price by no more than d bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.

Note, Polycarpus counts only the trailing nines in a price.

Input

The first line contains two integers p and d (1 ≤ p ≤ 10180 ≤ d < p) — the initial price of scissors and the maximum possible price reduction.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Output

Print the required price — the maximum price that ends with the largest number of nines and that is less than p by no more than d.

The required number shouldn't have leading zeroes.

Examples
input
1029 102
output
999
input
27191 17
output
27189

题意:求出[p-d, p]区间内末尾最多9的数,若答案有多个输出值最大的那个。

思路:贪心思想,设q = p-d(q位数与p位数对齐,若高位不足补0),从q和p的最高位开始比较,如果某一位置(pos)q的值(q[pos] = i)比p的值(p[pos] = j)小,将q这pos位以后的低数位全部设为9,然后判断将q[pos]设为j后q值有无超出p,无就q[pos]设为j,否则q[pos]设为j-1。

# include <stdio.h>long long solve(int len, int a[], int b[]){    bool flag = true;    for(int i=len; i>=0; --i)    {        if(b[i] < a[i])        {            for(int j=i-1; j>=0; --j)            {                b[j] = 9;                if(a[j] < 9)                    flag = false;            }            if(flag)                b[i] = a[i];            else                b[i] = a[i] - 1;            break;        }    }    int k;    long long ans = 0;    for(k=len; k>=0&&b[k]==0; --k);    for(int i=k; i>=0; --i)        ans = ans*10+b[i];    return ans;}int main(){    long long n, m;    while(~scanf("%lld%lld",&n,&m))    {        int k=0, a[20]={0}, b[20]={0};        m = n - m;        while(n)        {            a[k] = n%10;            b[k++] = m%10;            n /= 10;            m /= 10;        }        printf("%lld\n",solve(k-1, a, b));    }    return 0;}



0 0