AtCoder Beginner Contest 155 E.Payment

AtCoder Beginner Contest 155 E.Payment

Problem Statement

In the Kingdom of AtCoder, only banknotes are used as currency. There are
1 0 100 + 1 10^{100}+1 kinds of banknotes, with the values of 1 , 10 , 1 0 2 , 103 , , 1 0 1 0 100 . 1,10,10^2,103,…,10^{10^{100}} . You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.)
To make the payment, you will choose some amount of money which is at least
N and give it to the clerk. Then, the clerk gives you back the change, which is the amount of money you give minus N.

What will be the minimum possible number of total banknotes used by you and the clerk, when both choose the combination of banknotes to minimize this count?

Assume that you have sufficient numbers of banknotes, and so does the clerk.

Constraints N is an integer between 1 and 1 0 1 , 000 , 000 10^{1,000,000} (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible number of total banknotes used by you and the clerk.

Sample Input 1

36

Sample Output 1

8

Sample Input 2

 
91

Sample Output 2

3

Sample Input 3

314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170

Sample Output 3

243

这道题比较巧妙,最优的方法如下:
针对某一位数 x x ,我们用 a n s ans 直接记录每一位所需的钞票数,用 r e s res 记录进位所需的钞票数,若
1. x x 小于5,则答案直接加上 x x
2. x x 大于5,则答案直接加上 10 x 10-x
3.比较难考虑的就是 x = 5 x=5 的情况,你说四舍五入,那么假设 n = 5 n=5 时就不对,你如果进位的话就是一共付了6张,正确答案是5张;你说不进,那么假设 n = 995 n=995 ,你进位后就是 1005 1005 ,一共付了7张,正确答案是6张。通过我的举例你不难发现, x = 5 x=5 要进位只需它的前一位大于等于5即可
P S : PS: 此处有一个小技巧,就是在字符串开头加一个 0 '0' ,以防首位进位,不难发现,这样并不影响结果

知道最优解就非常简单了,AC代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
   string s;
   cin>>s;
   int ans=0,res=0;
   s='0'+s;
   int len=s.size();
   for(int i=len-1;i>=1;i--){//先算进位所需的钞票数
       if(i==0) continue;
        if(s[i]>'5') {
            res+=10-(s[i]-'0');
            s[i]='0';
            s[i-1]++;
        }
        else if(s[i]=='5' && s[i-1]>='5'){//再算每一位所需的钞票数
            res+=10-(s[i]-'0');
            s[i]='0';
            s[i-1]++;
        }
   }
   for(int i=0;i<len;i++)
       ans+=s[i]-'0';
   cout<<ans+res;
   return 0;
}
发布了288 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/104352487