a433中等逐組取最佳・延後篩選
APCS 2016/10:最大和 (ZeroJudge c295)
先從每組選最大值湊出總和,再依總和的整除條件輸出所選數字。
這題在學什麼
每組必須恰好選一個數字,而且目標是讓總和最大,因此每一組都獨立選該組最大值。先把這 N 個數加總得到 S。
選擇完成後才檢查每個所選數是否能整除 S。即使同一數值出現多次,也要按原群組逐一輸出;若沒有任何數能整除 S,就輸出 -1。
Step-by-step animation
每組最大值與總和
步驟 1 / 3
第一組
第一組在 1、5 中選最大值 5。
1
5
6
4
1
1
- 選取
- 5
- S
- 5
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> chosen(n);
int sum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int x; cin >> x;
if (j == 0 || x > chosen[i]) chosen[i] = x;
}
sum += chosen[i];
}
cout << sum << '\n';
bool found = false;
for (int x : chosen) {
if (sum % x == 0) {
if (found) cout << ' ';
cout << x;
found = true;
}
}
if (!found) cout << -1;
cout << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。