1012. 数字分类 (20)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
给定一系列正整数,请按要求对数字进行分类,并输出以下5个数字:
输入格式:
每个输入包含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
分析:题目本身不难,就是比较麻烦。这里为了练习vector的使用选择用vector来写。输入的数经过筛选塞到vector里面,按要求操作。最后根据条件判断输出‘N’还是数字个数。
代码:
#include<iostream> #include<vector> #include<iomanip> using namespace std; int main() { cout.precision(1); vector<int> A1, A2, A3, A4, A5; int a1 = 0, a2 = 0, a3 = 0, a5 = 0; double a4 = 0.0; int n; int temp; cin >> n; for(int i = 0; i < n; i++){ cin >> temp; if(temp % 5 == 0){ A1.push_back(temp); }else if(temp % 5 == 1){ A2.push_back(temp); }else if(temp % 5 == 2){ A3.push_back(temp); }else if(temp % 5 == 3){ A4.push_back(temp); }else if(temp % 5 == 4){ A5.push_back(temp); } } int cnt = 0; for(vector<int>::iterator it = A1.begin(); it != A1.end(); it++){ if(*it % 2 == 0){ a1 += *it; cnt++; } } int flag = 1; for(vector<int>::iterator it = A2.begin(); it != A2.end(); it++){ a2 += flag * (*it); flag *= -1; } a3 = A3.size(); for(vector<int>::iterator it = A4.begin(); it != A4.end(); it++){ a4 = a4 + (double)(*it) / A4.size(); } int maxN = -9999; for(vector<int>::iterator it = A5.begin(); it != A5.end(); it++){ if((*it) > maxN){ maxN = (*it); } } a5 = maxN; if(A1.size() == 0 || cnt == 0){ cout << "N "; }else{ cout << a1 << ' '; } if(A2.size() == 0){ cout << "N "; }else{ cout << a2 << ' '; } if(A3.size() == 0){ cout << "N "; }else{ cout << a3 << ' '; } if(A4.size() == 0){ cout << "N "; }else{ cout << fixed << a4 << ' '; } if(A5.size() == 0){ cout << "N" << endl; }else{ cout << a5 << endl; } return 0; }