Luba And The Ticket CodeForces - 845B

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.

Example
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.

每一位都選差最大的就可以了 比如前三位比後三位小 那就前三位裏找9-該位 差最大的 然後後三位裏找最大的 選他們倆中最大的 。

#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;

int main()
{
    char s[10];
    int a[10],b[10];
    while(scanf("%s",s)!=-1)
    {
        int sum1=0,sum2=0;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        for(int i=0;i<3;i++)
            a[i]=s[i]-'0',sum1+=a[i];
        for(int i=3;i<6;i++)
            b[i-3]=s[i]-'0',sum2+=b[i-3];
        int tmp=sum1-sum2;
        //cout<<tmp<<endl;
        sort(a,a+3);
        sort(b,b+3);
        if(tmp==0)
            cout<<"0"<<endl;
        else
        {
            if(tmp<0)
            {
                tmp=-tmp;
                int ans=0;
                int i=0,j=2;
                while(tmp>0)
                {
                    int f1,f2;
                    f1=9-a[i];
                    f2=b[j];
                    if(f1>=f2)
                    {
                        tmp-=f1;
                        i++;

                    }
                    else
                        tmp-=f2,j--;
                    ans++;
                }
                printf("%d\n",ans);
            }
            else
            {

                int ans=0;
                int i=0,j=2;
                while(tmp>0)
                {
                    int f1,f2;
                    f1=9-b[i];
                    f2=a[j];
                    if(f1>=f2)
                    {
                        tmp-=f1;
                        i++;

                    }
                    else
                        tmp-=f2,j--;
                    ans++;
                }
                printf("%d\n",ans);
            }
        }

    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章