PAT B1012 数字分类
### 输入样例 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
-
思路1:
分别用不同的变量累加,求出A1~A5 -
code1:
#include <stdio.h>
const int maxn = 1100;
int main(){
int N, a[maxn];
scanf("%d", &N);
for(int i = 0; i < N; ++i){
// scanf("%d ", &a[i]);
scanf("%d",&a[i]); //!!!:Wrong:不能多加空格,不晓得怎么回事
}
int ans1 = 0; //5整除 的 偶数 和
int ans2 = 0; //余1 交错和
bool flag = true, yes[5] = {false}; //+-标志,true:+
int cnt = 0; //余2 个数
double avg = 0; //余3 平均数
int cnt2 = 0;
int max = -1; //余4 最大数
for(int i = 0; i < N; ++i){
if(a[i] % 5 == 0 && a[i] % 2 == 0){
//i整除5 且 是偶数
ans1 += a[i];
yes[0] = true;
}else if(a[i] % 5 == 1){
yes[1] = true;
if(flag){
ans2 += a[i];
flag = false;
}else{
ans2 -= a[i];
flag = true;
}
}else if(a[i] % 5 == 2){
yes[2] = true;
cnt++;
}else if(a[i] % 5 == 3){
yes[3] = true;
avg += a[i];
cnt2++;
}else if(a[i] % 5 == 4){
yes[4] = true;
if(a[i] > max) max = a[i];
}
}
if(yes[0])
printf("%d ", ans1);
else printf("N ");
if(yes[1])
printf("%d ", ans2);
else printf("N ");
if(yes[2])
printf("%d ", cnt);
else printf("N ");
if(yes[3])
printf("%.1lf ", avg/cnt2);
else printf("N ");
if(yes[4])
printf("%d", max);
else printf("N");
return 0;
}
- 思路:
优化:直接用两个数组,一个记录不同类数字的个数,一个计算结果 - code2:
#include <stdio.h>
const int maxn = 1100;
int main(){
int count[5] = {0} , ans[5] = {0}; //一个统计不同数的个数, 一个计算结果
int n, tmp; //边输入边处理
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d", &tmp);
if(tmp % 5 == 0 && tmp % 2 == 0){//A1
ans[0] += tmp;
count[0]++;
}else if(tmp % 5 == 1){//A2
if((++count[1]) % 2 == 0){//偶数次:-
ans[1] -= tmp;
}else ans[1] += tmp;
}else if(tmp % 5 == 2){//A3
count[2]++;
}else if(tmp % 5 == 3){//A4
count[3]++;
ans[3] += tmp;
}else if(tmp % 5 == 4){//A5
count[4]++;
if(ans[4] <= tmp) ans[4] = tmp;
}
}
if(count[0] != 0)
printf("%d ", ans[0]);
else printf("N ");
if(count[1] != 0)
printf("%d ", ans[1]);
else printf("N ");
if(count[2] != 0)
printf("%d ", count[2]);
else printf("N ");
if(count[3] != 0)
printf("%.1lf ", (double)ans[3]/count[3]);
else printf("N ");
if(count[4] != 0)
printf("%d", ans[4]);
else printf("N");
return 0;
}