来源:北京大学考研机试题
优化前
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 100010; int a[N],b[N]; double jidian(int x) { if(x >= 90 && x <= 100) return 4.0; else if(x >= 85 && x <= 89) return 3.7; else if(x >= 82 && x <= 84) return 3.3; else if(x >= 78 && x <= 81) return 3.0; else if(x >= 75 && x <= 77) return 2.7; else if(x >= 72 && x <= 74) return 2.3; else if(x >= 68 && x <= 71) return 2.0; else if(x >= 64 && x <= 67) return 1.5; else if(x >= 60 && x <= 63) return 1.0; else return 0; } int main() { int n; double sum=0.0,cnt=0; scanf("%d\n", &n); for (int i = 0; i < n; i ++ ) { scanf("%d", &a[i]); cnt+=a[i]; } for (int i = 0; i < n; i ++ ) { scanf("%d", &b[i]); } for (int i = 0; i < n; i ++ ) { sum+=jidian(b[i])*a[i]; } printf("%.2f",sum/cnt); }
优化后
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 20; int key[10] = {0, 60, 64, 68, 72, 75, 78, 82, 85, 90}; double value[10] = {0, 1.0, 1.5, 2.0, 2.3, 2.7, 3.0, 3.3, 3.7, 4.0}; int a[N], b[N]; double jidian(int x) { for (int i = 9; i >= 0; i -- ) if (x >= key[i]) return value[i]; return 0; } int main() { int n; cin >> n; for (int i = 0; i < n; i ++ ) cin >> a[i]; for (int i = 0; i < n; i ++ ) cin >> b[i]; double sum = 0, cnt = 0; for (int i = 0; i < n; i ++ ) { sum += jidian(b[i]) * a[i]; cnt += a[i]; } printf("%.2lf\n", sum / cnt); return 0; }