这个整除36的与整除45的完全一样,就是被4整除的有点多,但都是两位数,所以枚举后面两位就可以了.
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = ;
const int M = ;
const int dir[][] = { {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }
}; int tmp, rec[M], cnt[M];
int n, s[N], x, id;
bool flag;
char ans[N]; void init()
{
char num[N];
scanf("%s", num);
x = strlen(num), tmp = ; flag = false;
memset(rec, , sizeof(rec));
memset(ans, , sizeof(ans)); for (int i = ; i < x; i++)
{
int cur = num[i] - '';
tmp += cur;
rec[cur]++;
}
}
void put(int a[], int d, char *str)
{
int len = ;
for (int i = ; i >= ; i--)
{
for (int j = ; j < a[i]; j++)
str[len++] = i + '';
}
for (int i = ; i < ; i++)
str[len++] = dir[d][i] + '';
str[len] = '\0';
} bool cmp(char *a, char *b)
{
for (int i = ; a[i]; i++)
{
if (a[i] != b[i]) return a[i] < b[i];
}
return false;
} void judge(int m)
{ char now[N];
put(cnt, id, now);
if (m < x || (cmp(ans, now) && m == x))
{
flag = true;
x = m;
strcpy(ans, now);
}
} void dfs(int m, int d, int sum)
{ if (d >= m)
{
if ((sum - tmp) % == ) judge(m);
return;
} for (int i = ; i <= ; i++)
{
if (!cnt[i]) continue;
cnt[i]--;
dfs(m, d + , sum + i);
cnt[i]++;
}
} void search(int d)
{
for (int i = ; i < ; i++)
{
cnt[dir[d][i]]--;
if (cnt[dir[d][i]] < ) return;
}
id = d;
for (int i = ; i <= tmp && i <= x; i++)
dfs(i, , );
} bool isOK(char *str)
{
int sum = , len = strlen(str);
if (len == && rec[] == ) return false;
for (int i = ; i < len; i++)
sum += str[i] - '';
return !sum;
} void solve()
{ for (int i = ; i < ; i++)
{
memcpy(cnt, rec, sizeof(rec));
search(i);
}
if (isOK(ans)) printf("0\n");
else if (flag) puts(ans);
else printf("impossible\n");
} int main()
{
int cas;
scanf("%d", &cas);
for (int i = ; i <= cas; i++)
{ init();
printf("Case %d: ", i);
solve();
}
return ;
}