C - Luba And The Ticket
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.
InputYou 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.
Print one number — the minimum possible number of digits Luba needs to replace to make the ticket lucky.
000000
0
123456
2
111000
1
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<algorithm>
using namespace std;
int main()
{
char s[6];
int a[6];
int b[3];
int c[3];
cin>>s;
for(int i=0;i<6;i++)
a[i]=s[i]-'0';
int l=a[0]+a[1]+a[2];
int r=a[3]+a[4]+a[5];
int h;
int k1=0,k2=0;
for(int i=0;i<=2;i++)
b[k1++]=a[i];
sort(b,b+3);
for(int i=3;i<=5;i++)
c[k2++]=a[i];
sort(c,c+3);
if(l==r)
cout<<"0"<<endl;
else if(l<r)
{
h=r-l;
if(c[2]>=h || b[0]<=9-h) //最大变小||最小变大
cout<<"1"<<endl;
else if(c[2]+c[1]>=h || 9-b[0]+9-b[1]>=h || 9-b[0]+c[2]>=h)
cout<<"2"<<endl;
else
cout<<"3"<<endl;
}
else
{
h=l-r;
if(b[2]>=h || c[0]<=9-h) //最大变小||最小变大
cout<<"1"<<endl;
else if(b[2]+b[1]>=h || 9-c[0]+9-c[1]>=h || 9-c[0]+b[2]>=h)
cout<<"2"<<endl;
else
cout<<"3"<<endl;
}
return 0;
}