cf-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.
You are given a string consisting of 6 characters (all characters are digits from 0to 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 <bits/stdc++.h>
using namespace std;
bool cmp(int a,int b) {
return a > b;
}
int main(int argc, char const *argv[]) {
char str[10];
scanf("%s",str);
int a = 0;
for(int i=0; i < 3; i++)
a = a+ str[i] - '0';
int b = 0;
for(int i=3; i < 6; i++)
b = b + str[i] - '0';
if(a==b)
puts("0");
else if(a<b) {
int ans = b - a;
int num[10];
for(int i=0;i < 3;i++)
num[i] = 9 - (str[i] - '0');
for(int i=3;i < 6;i++)
num[i] = (str[i]-'0');
sort(num,num+6,cmp);
for(int i=1; i<6;i++)
num[i] = num[i-1] +num[i];
for(int i=0;i<6;i++)
if(num[i]>=ans) {
printf("%d\n",i+1);
break;
}
}
else {
int ans = a - b;
int num[10];
for(int i=3;i < 6;i++)
num[i] = 9 - (str[i] - '0');
for(int i=0;i < 3;i++)
num[i] = str[i] - '0';
sort(num,num+6,cmp);
for(int i=1; i<6;i++)
num[i] = num[i-1] +num[i];
for(int i=0;i<6;i++)
if(num[i]>=ans) {
printf("%d\n",i+1);
break;
}
}
return 0;
}
下面是网上
点击打开链接