HDU-4726-K

来源:互联网 发布:自我管理的软件 编辑:程序博客网 时间:2024/06/05 05:43

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

这题要用到贪心。。。。

#include <cstdio>#include <cstring>using namespace std;const int maxn=1e6+5;char num1[maxn],num2[maxn],ans[maxn];int i[10],j[10];int main(){    int t;    scanf("%d\n",&t);    for(int k = 1; k <= t; k ++)    {        memset(i,0,sizeof(i));        memset(j,0,sizeof(j));        scanf("%s%s",num1,num2);        int len = strlen(num1);        if(len==1)        {            printf("Case #%d: %d\n",k,(num1[0]+num2[0]-96)%10);            continue;        }        for(int a = 0; a < len; a ++)        {            i[num1[a]-48]++;            j[num2[a]-48]++;        }        for(int d = 0; d < len; d ++)        {            bool flag=false;            for(int b = 9; b >= 0&&(!flag); b--)            {                for(int c = 0; c <= 9&&(!flag); c ++)                {                    if(b-c>=0)                    {                        if(!(d==0&&(b-c==0||c==0)))                            if(i[c]>0&&j[b-c]>0)                            {                                i[c]--;                                j[b-c]--;                                flag=true;                                ans[d]=b+'0';                                break;                            }                    }                    else                    {                        if(i[c]>0&&j[b+10-c]>0)                        {                            i[c]--;                            j[b+10-c]--;                            flag=true;                            ans[d]=b+'0';                            break;                        }                    }                }            }        }    ans[len]='\0';    if(ans[0]=='0')    {        printf("Case #%d: 0\n",k);    }    else        printf("Case #%d: %s\n",k,ans);}return 0;}
原创粉丝点击