1. 程式人生 > >【大家都能看得懂的演算法題】 1012 數字分類

【大家都能看得懂的演算法題】 1012 數字分類

1012 數字分類

給定一系列正整數,請按要求對數字進行分類,並輸出以下5個數字:

A1 = 能被5整除的數字中所有偶數的和;

A2 = 將被5除後餘1的數字按給出順序進行交錯求和,即計算n1-n2+n3-n4…;

A3 = 被5除後餘2的數字的個數;

A4 = 被5除後餘3的數字的平均數,精確到小數點後1位;

A5 = 被5除後餘4的數字中最大數字。

輸入格式:
每個輸入包含1個測試用例。每個測試用例先給出一個不超過1000的正整數N,隨後給出N個不超過1000的待分類的正整數。數字間以空格分隔。

輸出格式:
對給定的N個正整數,按題目要求計算A1~A5並在一行中順序輸出。數字間以空格分隔,但行末不得有多餘空格。
若其中某一類數字不存在,則在相應位置輸出“N”。

輸入樣例1:
13 1 2 3 4 5 6 7 8 9 10 20 16 18
輸出樣例1:
30 11 2 9.7 9
輸入樣例2:
8 1 2 4 5 6 7 9 16
輸出樣例2:
N 11 2 N 9

分析

主要是取餘操作,沒有什麼難點,可能考printf是否熟悉保留位數吧。


#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath> #include <iomanip> using namespace std; int main() { int numOfInput; cin >> numOfInput; vector<long> a1; vector<long> a2; vector<long> a3; vector<long> a4; vector<long> a5; for (int i = 0; i < numOfInput; ++i) { int
num; cin >> num; if (num % 5 == 0 && num % 2 == 0) a1.push_back(num); if (num % 5 == 1) a2.push_back(num); if (num % 5 == 2) a3.push_back(num); if (num % 5 == 3) a4.push_back(num); if (num % 5 == 4) { a5.push_back(num); } } //A1 = 能被 5整除 的數字中所有 偶數 的 和; // //A2 = 將被 5除後餘1 的數字按給出順序進行 交錯求和 ,即計算n1-n2+n3-n4...; // //A3 = 被 5除後餘2 的數字的 個數; // //A4 = 被 5除後餘3 的數字的 平均數 ,精確到小數點 後1位; // //A5 = 被 5除後餘4 的數字中 最大數字 long A1 = 0; for (int i = 0; i < a1.size(); ++i) A1 += a1[i]; long A2 = 0; for (int i = 0; i < a2.size(); ++i) { A2 += a2[i] * pow(-1.0, 1.0 * i); } long A3 = a3.size(); double A4 = 0; double cache = 1.0 / a4.size(); for (int i = 0; i < a4.size(); ++i) { A4 += a4[i] * cache; } long A5 = 0; if (!a5.empty()) A5 = a5[0]; for (int i = 1; i < a5.size(); ++i) { if (a5[i] > A5) { A5 = a5[i]; } } if (!a1.empty()) { printf("%d ", A1); } else { printf("%s ", "N"); } if (!a2.empty()) { printf("%d ", A2); } else { printf("%s ", "N"); } if (!a3.empty()) { printf("%d ", A3); } else { printf("%s ", "N"); } if (!a4.empty()) { printf("%.1f ", A4); } else { printf("%s ", "N"); } if (!a5.empty()) { printf("%d\n", A5); } else { printf("%s\n", "N"); } }