本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
Doctor Ghee is teaching Kia how to calculate the sum of two integers. But Kia is so careless and alway forget to carry a number when the sum of two digits exceeds 9. For example, when she calculates 4567+5789, she will get 9246, and for 1234+9876, she will get 0. Ghee is angry about this, and makes a hard problem for her to solve:
Now Kia has two integers A and B, she can shuffle the digits in each number as she like, but leading zeros are not allowed. That is to say, for A = 11024, she can rearrange the number as 10124, or 41102, or many other, but 02411 is not allowed.
After she shuffles A and B, she will add them together, in her own way. And what will be the maximum possible sum of A “+” B ?
Input
The rst line has a number T (T <= 25) , indicating the number of test cases.
For each test case there are two lines. First line has the number A, and the second line has the number B.
Both A and B will have same number of digits, which is no larger than 10 6, and without leading zeros.
Output
For test case X, output "Case #X: " first, then output the maximum possible sum without leading zeros.
Sample Input
1
5958
3036
Sample Output
Case #1: 8984
分析:
贪心构造,思路大体就是桶排一波,然后贪心构造。
一开始本不想写这个博客的,但是我wa了好久。也是在此引以为戒。
我们对每个字符串进行桶排,把第一个数要特殊构造,因为不能有前导0.其他数直接构造即可;
#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
int T;
char s1[1001001],s2[1001001];
int num1[11],num2[11];
int main()
{
scanf("%d",&T);
int cnt = 1;
while(T --)
{
scanf("%s%s",s1 + 1,s2 + 1);
printf("Case #%d: ",cnt ++);
if(s1[1] == '0' || s2[1] == '0')//这种情况需要特判
{
if(s1[1] == '0')
printf("%d\n",s2[1] - '0');
else
printf("%d\n",s1[1] - '0');
continue;
}
int len = strlen(s1 + 1);
for(int i = 0; i <= 9; i ++)//sb错误,未能每次清0
{
num1[i] = num2[i] = 0;
}
for(int i = 1; i <= len; i ++)
{
num1[s1[i] - '0'] ++;
num2[s2[i] - '0'] ++;
}
int digit = 9,mark = 1;
while(digit)
{
for(int i = 9; i >= 0; i --)
{
if(num1[i] == 0)
continue;
for(int j = 0; j <= 9; j ++)
{
if(num2[j] == 0)
continue;
if((i + j) % 10 == digit && i != 0 && j != 0)
{
printf("%d",digit);
mark = 0;
num1[i] --;
num2[j] --;
break;
}
}
if(mark == 0)
break;
}
if(mark == 0)
break;
digit --;
}
if(digit == 0)//这种也需要特判一下
{
printf("0\n");
continue;
}
digit = 9;
while(digit >= 0)
{
for(int i = 9; i >= 0; i --)
{
if(num1[i] == 0)
continue;
for(int j = 9; j >= 0; j --)
{
if(num2[j] == 0 || num1[i] == 0)//这里一开始未判num1[i]了 傻逼呀
continue;
if((i + j) % 10 == digit)
{
printf("%d",digit);
num1[i] --;
num2[j] --;
j ++;
}
}
}
digit --;
}
printf("\n");
}
}
/*
1010
12345567888
12345654876
0
0
0
1
55
55
*/