#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int mask(int n) {
int mask = 0;
for (int i = 1; n/i; i*= 10) {
int digit = n/i % 10;
mask |= 1 << digit;
}
return mask;
}
int dp(int set, int memo[1<<10], const vector<int>& a) {
if (set == 0) {
return memo[set] = 0;
}
if (memo[set] != -1)
return memo[set];
int res = 0;
for (auto num: a) {
int bitmask = mask(num);
if ((set | bitmask) == set)
res = std::max(dp(set ^ mask(num), memo, a) + num, res);
}
return memo[set] = res;
}
int main()
{
vector<int> a = {121,23,3,333,4};
int memo[1<<10];
for (int i = 0; i < 1 << 10; i++) memo[i] = -1;
int res = 0;
for (int i = 0; i < 1 << 10; i++) {
res = std::max(res, dp(i, memo, a));
}
cout << res << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBtYXNrKGludCBuKSB7CiAgaW50IG1hc2sgPSAwOwogIGZvciAoaW50IGkgPSAxOyBuL2k7IGkqPSAxMCkgewogICAgaW50IGRpZ2l0ID0gbi9pICUgMTA7CiAgICBtYXNrIHw9IDEgPDwgZGlnaXQ7CiAgfQogIHJldHVybiBtYXNrOwp9CgppbnQgZHAoaW50IHNldCwgaW50IG1lbW9bMTw8MTBdLCBjb25zdCB2ZWN0b3I8aW50PiYgYSkgewogIGlmIChzZXQgPT0gMCkgewogICAgcmV0dXJuIG1lbW9bc2V0XSA9IDA7CiAgfQogIGlmIChtZW1vW3NldF0gIT0gLTEpCiAgICByZXR1cm4gbWVtb1tzZXRdOwoKICBpbnQgcmVzID0gMDsKICBmb3IgKGF1dG8gbnVtOiBhKSB7CiAgICBpbnQgYml0bWFzayA9IG1hc2sobnVtKTsKICAgIGlmICgoc2V0IHwgYml0bWFzaykgPT0gc2V0KQogICAgICByZXMgPSBzdGQ6Om1heChkcChzZXQgXiBtYXNrKG51bSksIG1lbW8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