cfB. Luba And The Ticket time limit per test2 seconds memory limit per test256 megabytes inputstanda

本文介绍了一个有趣的问题:如何通过最少的数字替换使一张由六个数字组成的票变得“幸运”。所谓幸运票,即前三个数字之和等于后三个数字之和。文章通过分析不同情况给出了最优解决方案,并附上了实现这一算法的C++代码。
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.


这题没能在2小时内做出来,但是也并不难。

开始的思路就是找规律,如果暴力求解,问题会复杂化。

感觉会有个坑,就是答案为2时,除了18-小的和的两个最小数  以及  大的和的2个最大数 还有 一个打的和最大+9-一个小的和最小。

思路就是判1时 ,当然为 大的和的最大值 或者 小的和的9-最小  为活动范围。这写起来有点麻烦,看代码把

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int a[220];
int main()
{

    int A[3],B[3],a[3],b[3];
    for(int i=0;i<6;i++){
        char x;
        scanf("%c",&x);
        if(i<3){ A[i]=x-'0'; }
        else B[i-3]=x-'0';
    }
    int sum1,sum2;
    int s1=A[0]+A[1]+A[2];
    int s2=B[0]+B[1]+B[2];
    if(s1>s2){
        b[0]=A[0];
        b[1]=A[1];
        b[2]=A[2];
        a[0]=B[0];
        a[1]=B[1];
        a[2]=B[2];
        sum2=s1;
        sum1=s2;
    }
    else {
        b[0]=B[0];
        b[1]=B[1];
        b[2]=B[2];
        a[0]=A[0];
        a[1]=A[1];
        a[2]=A[2];
        sum2=s2;
        sum1=s1;
    }


    sort(a,a+3);
    sort(b,b+3);


    int tmp=abs(sum1-sum2);
    if(tmp==0) printf("0");
    else if(tmp<=b[2]||tmp<=(9-a[0])) printf("1");
    else if(tmp<=b[2]+b[1]||tmp<=(18-a[0]-a[1])||tmp<=b[2]+9-a[0]) printf("2");
    else printf("3");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值