Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3291 Accepted Submission(s): 703
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 <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #define LL long long using namespace std; const int N = 1000005; char str1[N],str2[N]; int num1[20],num2[20]; int res[N]; int main() { int tcase,t = 1; scanf("%d",&tcase); while(tcase--) { scanf("%s%s",str1,str2); if(strcmp(str1,"0")==0){ printf("Case #%d: ",t++); printf("%s\n",str2); continue; } if(strcmp(str2,"0")==0){ printf("Case #%d: ",t++); printf("%s\n",str1); continue; } int len = strlen(str1); memset(num1,0,sizeof(num1)); memset(num2,0,sizeof(num2)); for(int i=0; i<len; i++) { num1[str1[i]-'0']++; num2[str2[i]-'0']++; } int high = -1,x,y; for(int i=1; i<=9; i++) { for(int j=1; j<=9; j++) { if(num1[i]&&num2[j]&&high<(i+j)%10) { x = i; y = j; high = (i+j)%10; } } } num1[x]--; num2[y]--; int cnt = 0,zero = 0; res[cnt++] = high; if(high==0) zero++; printf("Case #%d: ",t++); if(zero){ printf("0\n"); continue; } for(int l=1; l<len; l++) { /* TLE for(int i=0; i<=9; i++) { for(int j=0; j<=9; j++) { if(num1[i]&&num2[j]&&MAX<(i+j)%10) { x = i; y = j; MAX = (i+j)%10; } } }*/ bool flag = true; for(int i=9;i>=0&&flag;i--){ for(int j=0;j<=9&&flag;j++){ if(i-j<0&&num1[j]&&num2[i-j+10]){ num1[j]--; num2[i-j+10]--; res[cnt++] = i; flag = false; }else if(i-j>=0&&num1[j]&&num2[i-j]){ num1[j]--; num2[i-j]--; res[cnt++] = i; flag = false; } } } } for(int i=0;i<cnt;i++){ printf("%d",res[i]); } printf("\n"); } return 0; }