今天又是超时的一天,大家一定也要注意一下尽可能的减少空间复杂度,能省则省!!!
题目描述
background:
A new semester comes , and the HDU also meets its 50th birthday. No matter what’s your major, the only thing I want to tell you is:“Treasure the college life and seize the time.” Most people thought that the college life should be colorful, less presure.But in actual, the college life is also busy and rough. If you want to master the knowledge learned from the book, a great deal of leisure time should be spend on individual study and practise, especially on the latter one. I think the every one of you should take the learning attitude just as you have in senior school.
“No pain, No Gain”, HDU also has scholarship, who can win it? That’s mainly rely on the GPA(grade-point average) of the student had got. Now, I gonna tell you the rule, and your task is to program to caculate the GPA.
If there are K(K > 0) courses, the i-th course has the credit Ci, your score Si, then the result GPA is
GPA = (C1 * S1 + C2 * S2 +……+Ci * Si……) / (C1 + C2 + ……+ Ci……) (1 <= i <= K, Ci != 0)
If there is a 0 <= Si < 60, The GPA is always not existed.
输入
The first number N indicate that there are N test cases(N <= 50). In each case, there is a number K (the total courses number), then K lines followed, each line would obey the format: Course-Name (Length <= 30) , Credits(<= 10), Score(<= 100).
Notice: There is no blank in the Course Name. All the Inputs are legal
输出
Output the GPA of each case as discribed above, if the GPA is not existed, ouput:“Sorry!”, else just output the GPA value which is rounded to the 2 digits after the decimal point. There is a blank line between two test cases.
代码
超时代码示范
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char name[50][30];
double C[50], S[50];
int N, M, i, p;
double score, sum;
cin >> N;
while (N--) {
p = 0;
score = 0; sum = 0;
cin >> M;
for (i = 0; i < M; i++) cin >> name[i] >> C[i] >> S[i];
for (i = 0; i < M; i++) {
score += C[i] * S[i];
sum += C[i];
if (S[i] < 60) {
p = 1;
break;
}
}
if (p == 1) cout << "Sorry!" << endl;
else {
score = score * 1.0 / sum;
cout << fixed << setprecision(2) << score << endl << endl;
}
}
return 0;
}
为什么上面的代码会超时,因为创建了大量的空间,比如char name[50][30]; double C[50], S[50];
如果读者没有犯这个错误,那可以直接对比看下面的代码.
创建的这些空间,完全可以在一个for
循环中读取和计算,因此要提高警惕,不需要的空间我们就省下来,不然会提示超时.
正确的AC代码来了
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char name[31];
double C, S;
int N, M, i, p;
double score, sum;
cin >> N;
while (N--) {
p = 0;
score = 0; sum = 0;
cin >> M;
for (i = 0; i < M; i++) {
cin >> name >> C >> S;
score += C * S;
sum += C;
if (S < 60) {
p = 1;
}
}
if (p == 1) cout << "Sorry!" << endl;
else {
score = score * 1.0 / sum;
cout << fixed << setprecision(2) << score << endl;
}
if (N != 0) cout << endl;
}
return 0;
}
加油,每天进步一点点!