Kia's Calculation
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 588 Accepted Submission(s): 158
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 ?
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 106, and without leading zeros.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[30],b[30];
char A[2000000],B[2000000];
int numa[2000000],numb[1000000];
int cnt[2000000];
int main()
{
int t,num=1,i,len,j,x,y,min,count,k;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",A,B);
len=strlen(A);
for(i=0; i<len; i++)
{
numa[i]=A[i]-'0';
numb[i]=B[i]-'0';
}
if(len==1)
{
printf("Case #%d: %d
",num++,(numa[0]+numb[0])%10);
continue;
}
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(i=0; i<len; i++)
{
a[numa[i]]++;
b[numb[i]]++;
}
for(k=0; k<len;)
{
min=-1;
for(i=0; i<=9; i++)
{
if(k==0&&i==0)
continue;
for(j=0; j<=9; j++)
{
if(k==0&&j==0)
continue;
if(a[i]&&b[j]&&(i+j)%10>min)
{
x=i;
y=j;
min=(x+y)%10;
}
}
}
a[x]--;
b[y]--;
cnt[k++]=min;
if(k>1)
{
while(a[x]>0&&b[y]>0) //剪枝,一旦找到比较大的,可以看看是否符合下一位
{
cnt[k++]=min;
a[x]--;
b[y]--;
}
}
}
printf("Case #%d: ",num++);
for(i=0;i<len;i++)
{
if(cnt[i]!=0)
break;
}
if(i==len)
{
printf("0
");
continue;
}
for(;i<len;i++)
printf("%d",cnt[i]);
printf("
");
}
return 0;
}