The number on the board

来源:互联网 发布:淘宝骗手机 编辑:程序博客网 时间:2024/06/07 04:45

题目链接  http://codeforces.com/problemset/problem/835/B

B. The number on the board
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.

You have to find the minimum number of digits in which these two numbers can differ.

Input

The first line contains integer k (1 ≤ k ≤ 109).

The second line contains integer n (1 ≤ n < 10100000).

There are no leading zeros in n. It's guaranteed that this situation is possible.

Output

Print the minimum number of digits in which the initial number and n can differ.

Examples
input
311
output
1
input
399
output
0
题目大意:

有一个数被替换掉了几个数字,现在只知道被改过的数,题目问被改过的数字至少改掉几个数字后能够回到原数(只要是符合各位数字之和>=k即可,所以原数有好多种可能,只要满足一种就行)
第一行的3表示原数每位数字之和>=3。第二行11表示被改过的数。只要把1改成2或者3或者4......(满足之和>=3)就行。所以改变一位数字即可,答案输出1。
解题思路:
k用整型存储没问题,但是n太大了,必须用字符串存储。先求n的各位数字之和,判断是否>=k。如果>=k,则输出0;如果不,就按从小到大的顺序排序n字符串,然后从头开始(也就是把最小数换成'9',然后判断改变后之和是否>=k),如果不,就继续吧第二小的数字改成‘9’,直到满足之和>=k,然后输出循环的次数就是答案。
代码:
#include<iostream>#include<algorithm>                 //sort排序函数需要用到的头文件using namespace std;int main(){    long long int k;    string s;    while(cin>>k>>s)    {        int summ=0,i;        sort(s.begin(),s.end());    //把s字符串从小到大排序        long long int sum=0;        //用于存储各位数字的和        for(int i=0;i<=s.size()-1;i++)   //计算各位数字之和            sum=sum+s[i]-'0';        if(sum>=k)                      //如果各位数字之和满足题意,说明不用改变数字,输出0            cout<<0<<endl;        else        {            k=k-sum;                    //否字的话,让k存储 满足题意的各位数字之和 与 目前各位数字之和 的 差值            for(i=0;i<=s.size()-1;i++)            {                summ=summ+'9'-s[i];           //从小的数字开始,计算如果把小的数字改为‘9’后,与目标(即上述k)的关系                if(summ>=k)                   //如果等于或者超过k,则满足题意                    break;            }            cout<<i+1<<endl;                 //i即为改变数字的个数        }    }    return 0;}