給定 n 個數字(0-9),選擇其中部分(可全選)組成一個整數,要求:
設所有數字和為 sum,cnt[d] 為數字 d 的出現次數。
sum % 3 == 0:直接按降序輸出所有數字(0 在末尾)。sum % 3 == 1:
{1,4,7} 中存在的數字。{2,5,8} 中的數字(因 2+2=4≡1, 5+5=10≡1, 8+8=16≡1 mod 3)。sum % 3 == 2:
{2,5,8}。{1,4,7}(1+1=2, 4+4=8≡2, 7+7=14≡2 mod 3)。
#include
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n) {
vector cnt(10, 0);
long long sum = 0;
for (int i = 0, x; i < n; ++i) {
cin >> x;
cnt[x]++;
sum += x;
}
if (cnt[0] == 0) {
cout << -1 << '\n';
continue;
}
auto remove_one = [&](const vector& digits) {
for (int d : digits) if (cnt[d] > 0) { cnt[d]--; return true; }
return false;
};
auto remove_two = [&](const vector& digits) {
int removed = 0;
for (int d : digits) {
while (cnt[d] > 0 && removed < 2) { cnt[d]--; removed++; }
}
return removed == 2;
};
bool ok = true;
if (sum % 3 == 1) {
if (!remove_one({1,4,7}) && !remove_two({2,5,8})) ok = false;
} else if (sum % 3 == 2) {
if (!remove_one({2,5,8}) && !remove_two({1,4,7})) ok = false;
}
if (!ok) {
cout << -1 << '\n';
continue;
}
bool all_zero = true;
for (int d = 1; d <= 9; ++d) if (cnt[d]) all_zero = false;
if (all_zero) {
cout << 0 << '\n';
} else {
for (int d = 9; d >= 0; --d)
while (cnt[d]--) cout << d;
cout << '\n';
}
}
return 0;
}
O(n + 10) ≈ O(n),僅涉及計數與常數次調整。O(1),固定大小計數數組。
輸入: 1 0 → 輸出: 0
輸入: 11 3 4 5 4 5 3 5 3 4 4 0 → 輸出: 5554443330
輸入: 8 3 2 5 1 5 2 2 3 → 輸出: -1