Codeforces Educational Codeforces Round 27 - B - Luba And The Ticket

B. Luba And The Ticket
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.

The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.

Input

You are given a string consisting of 6 characters (all characters are digits from 0 to 9) — this string denotes Luba's ticket. The ticket can start with the digit 0.

Output

Print one number — the minimum possible number of digits Luba needs to replace to make the ticket lucky.

Examples
input
000000
output
0
input
123456
output
2
input
111000
output
1
Note

In the first example the ticket is already lucky, so the answer is 0.

In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required.

In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required.


题意:给你一个六位数(可以有前导零),你可以将任意一位的数字变为任意其他数字,求最少变多少次使得前三个数字之和与后三个数字之和相等。


思路:贪心,每次改变数字都要使两个和接近的最多。


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int main()
{
    char s[10];
    while(cin>>s)
    {
        int sum[5]={0},add[10]={0};
        for(int i=0;i<6;i++)
            sum[i/3] += s[i] - '0',add[i] = '9' - s[i];
        if(sum[0]>=sum[1])
        {
            for(int i=0;i<3;i++)
                add[i] = 9 - add[i];
        }
        else
        {
            swap(sum[0],sum[1]);
            for(int i=3;i<6;i++)
                add[i] = 9 - add[i],swap(add[i-3],add[i]);
        }
        for(int i=0;i<6;i++)
        {
            if(sum[0]<=sum[1])
            {
                printf("%d\n",i);
                break;
            }
            int mx = 0,pos = -1;
            for(int j=0;j<6;j++)
            {
                if(mx<add[j])
                {
                    mx = add[j];
                    pos = j;
                }
            }
            add[pos] = 0;
            if(pos<3)
                sum[0] -=mx;
            else
                sum[1] +=mx;
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值