題目說明#
給 N 群數字,每群 M 個,找出每群最大的數字輸出其總和 S ,並判斷各群所選出的數字是否可以整除總和 S ,如果可以依序輸出,全都不行則輸出 -1 。
注意 : 題目輸出各群所選出的數字最後不能有空白。
解題過程#
首先先輸入 n, m ,因為二維的 sort 比較麻煩,可以先用一維陣列排序完後再複製過去二維陣列。
使用 greater 把群裡最大的數字排在最前面並加總得到總和 s 。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, s = 0, can = 1;
cin >> n >> m;
int ans[n][m];
vector<int> a(m);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> a[j];
}
sort(a.begin(), a.end(), greater<int>());
for(int j = 0; j < m; j++)
{
ans[i][j]= a[j];
}
s += a[0];
}
最後再依照題目要求輸出
cout << s << endl;
for(int i = 0; i < n; i++)
{
if(s % ans[i][0] == 0)
{
if(can) cout << ans[i][0];
else cout << ' ' << ans[i][0];
can = 0;
}
}
if(can) cout << "-1";
return 0;
}
程式碼就完成了 !
完整程式碼如下
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, s = 0, can = 1;
cin >> n >> m;
int ans[n][m];
vector<int> a(m);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> a[j];
}
sort(a.begin(), a.end(), greater<int>());
for(int j = 0; j < m; j++)
{
ans[i][j]= a[j];
}
s += a[0];
}
cout << s << endl;
for(int i = 0; i < n; i++)
{
if(s % ans[i][0] == 0)
{
if(can) cout << ans[i][0];
else cout << ' ' << ans[i][0];
can = 0;
}
}
if(can) cout << "-1";
return 0;
}
