codeforeces 845B

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

题目大意

给你一个长度为6的字符串,可以使任意数变为另一个数,问最多需要几次变换使前三个数的和等于后三个数的和。

样例

simple1
000000
0
simple2
123456
2
simple3
111000
1

思路

变换的情况只有4种,简单模拟一下就好了。

  1. 要使变换次数最少肯定是减少后三个中最大的
  2. 或是补上前三个中最小的到9(默认前三个的和小于后三个的),做几次变换就可以知道结果了

代码

#include
#include
#include
using namespace std;
const int inf=0x3f3f3f3f;  
char g[8];  
int sum1,sum2,a[3],b[3];  
void Swap(int a[3],int b[3])  
{  
    for(int i=0;i<3;i++) swap(a[i],b[i]);  
}  
  
int main()  
{  
    while(gets(g)!=NULL)  
    {  
        for(int i=0;i<3;i++)a[i]=g[i]-'0',sum1+=g[i]-'0';  
        for(int i=3;i<6;i++)b[i-3]=g[i]-'0',sum2+=g[i]-'0';  
        sort(a,a+3);  
        sort(b,b+3);  
        if(sum1>sum2)Swap(a,b),swap(sum1,sum2);//默认前面的三个小  
        int p=sum2-sum1;  
        if(!p)  
            printf("0\n");  
        else if(p<=9-a[0]||p<=b[2])//只有一个数字变换的最大情况  
            printf("1\n");  
        else if(p<=9-a[0]+9-a[1]||p<=b[2]+b[1]||p<=9-a[0]+b[2])//两个数字变换有三种情况  
            printf("2\n");  
        else  
            printf("3\n");  
    }  
    return 0;  
}  

你可能感兴趣的:(codeforeces 845B)