贪心 HDOJ 4726 Kia's Calculation

 

题目传送门

 1 /*  2  这题交给队友做,做了一个多小时,全排列,RE数组越界,赛后发现读题读错了,囧!  3  贪心:先确定最高位的数字,然后用贪心的方法,越高位数字越大  4  5  注意:1. Both A and B will have same number of digits 两个数字位数相同  6  2. which is no larger than 10 6 不是大小,而是长度不超过1e6  7 */  8 #include <cstdio>  9 #include <iostream>  10 #include <algorithm>  11 #include <cstring>  12 #include <string>  13 #include <cmath>  14 using namespace std;  15  16 const int MAXN = 1e6 + 10;  17 const int INF = 0x3f3f3f3f;  18 char s1[MAXN], s2[MAXN];  19  20 int main(void) //HDOJ 4726 Kia's Calculation  21 {  22 //freopen ("K.in", "r", stdin);  23  24 int t, cas = 0;  25 int cnt1[11], cnt2[11], cnt3[11];  26  27 scanf ("%d", &t);  28 while (t--)  29  {  30 scanf ("%s", &s1);  31 scanf ("%s", &s2);  32  33 printf ("Case #%d: ", ++cas);  34  35 int len = strlen (s1);  36 if (strcmp (s1, "0") == 0)  37  {  38 printf ("%s\n", s2); continue;  39  }  40 else if (strcmp (s2, "0") == 0)  41  {  42 printf ("%s\n", s1); continue;  43  }  44  45 memset (cnt1, 0, sizeof (cnt1));  46 memset (cnt2, 0, sizeof (cnt2));  47 memset (cnt3, 0, sizeof (cnt3));  48  49 for (int i=0; i<len; ++i)  50  {  51 cnt1[s1[i]-'0']++; cnt2[s2[i]-'0']++;  52  }  53  54 int ii = 1, jj = 1, mx = -1;  55 for (int i=1; i<=9; ++i)  56  {  57 if (cnt1[i] == 0) continue;  58 for (int j=1; j<=9; ++j)  59  {  60 if (cnt2[j] == 0) continue;  61 int tmp = (i + j) % 10;  62 if (tmp > mx)  63  {  64 mx = tmp; ii = i; jj = j;  65  }  66  }  67  }  68 cnt1[ii]--; cnt2[jj]--;  69 if (!mx)  70  {  71 puts ("0"); continue;  72  }  73  74 for (int i=9; i>=0; --i)  75  {  76 for (int j=0; j<=9; ++j)  77  {  78 for (int k=0; k<=9; ++k)  79  {  80 if ((j+k)%10==i && cnt1[j] && cnt2[k])  81  {  82 int tmp = min (cnt1[j], cnt2[k]);  83 cnt1[j] -= tmp; cnt2[k] -= tmp;  84 cnt3[i] += tmp;  85  }  86  }  87  }  88  }  89  90 printf ("%d", mx);  91 for (int i=9; i>=0; --i)  92  {  93 for (int j=0; j<cnt3[i]; ++j) printf ("%d", i);  94  }  95 puts ("");  96  }  97  98  99 return 0; 100 }

 

你可能感兴趣的:(IO)