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
题解:第一位都不能为前导0,所以第一位单独找,其余位,从大到小枚举找就可以了,注意的是,找第一位的时候从小的开始找,举个例子:480 280 如果从大开始 两个8就先选了。但是数据水了,第一位怎么找都是对的。从第二位往后,因为是枚举的数,所以怎么找都可以
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
const int N=1e6+10;
char a[N],b[N];
int n1[15],n2[15];
int ans[N],len;
int main()
{
int T,cas=1;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",a,b);
int len=strlen(a);
memset(n1,0,sizeof(n1));
memset(n2,0,sizeof(n2));
for(int i=0;i<len;i++)
{
n1[a[i]-'0']++;
n2[b[i]-'0']++;
}
printf("Case #%d: ",cas++);
if(len==1) printf("%d\n",(a[0]-'0'+b[0]-'0')%10);
else
{
int maxx=-1,p1,p2;
for(int i=1;i<=9;i++)
{
if(n1[i]==0) continue;
for(int j=1;j<=9;j++)
{
if(n2[j]==0) continue;
if((i+j)%10>maxx)
{
maxx=(i+j)%10;
p1=i;p2=j;
}
}
}
n1[p1]--;n2[p2]--;
len=0;
ans[len++]=maxx;
for(int i=9;i>=0;i--)
{
for(int j=0;j<=9;j++)
{
if(n1[j]==0) continue;
int cnt;
if(i>=j) cnt=i-j;
else cnt=i+10-j;
if(n2[cnt])
{
int minn=min(n1[j],n2[cnt]);
n1[j]-=minn;
n2[cnt]-=minn;
while(minn--) ans[len++]=i;
}
}
}
int i=0;
for(;i<len;i++)
if(ans[i])
break;
if(i<len)
{
for(;i<len;i++)
printf("%d",ans[i]);
printf("\n");
}
else printf("0\n");
}
}
return 0;
}