我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805270356541440
题目描述:
知识点:字符串、读取数据、计数
思路:将正确选项个数和其后的正确选项(包括其间的空格)当成一整个字符串进行比较
本题读入的数据甚多,但难度还是低的,注意以下几点:
(1)用一个大小为N的数组scores来保存各个学生的分数。
(2)用一个大小为M的数组countWrong来保存各题的错误次数。
(3)在用getline读取数据之前,需先用getchar()读取前一行遗留下来的换行符"\n"。
(4)cin读取字符时,会自动跳过空格。而scanf则不会跳过空格,会把空格也当成一个字符读进来。
(5)本题中,每题的选项个数是一个多余的条件,不需要保存和记录。
时间复杂度是O(N * M)。空间复杂度是O(M + N)。
C++代码:
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
struct question {
int score;
string trueOptionsAndAnswer;
};
int main() {
int N, M;
cin >> N >> M;
int tempScore;
int tempOptions;
int tempTrueOptions;
char tempAnswer;
question tempQuestion;
vector<question> questions;
for(int i = 0; i < M; i++) {
cin >> tempScore >> tempOptions >> tempTrueOptions;
tempQuestion.trueOptionsAndAnswer = "";
//use stringstream in head file <sstream> to merge int and string
stringstream ss(tempQuestion.trueOptionsAndAnswer);
ss << tempTrueOptions;
tempQuestion.trueOptionsAndAnswer = ss.str();
tempQuestion.trueOptionsAndAnswer += " ";
for(int i = 0; i < tempTrueOptions; i++) {
//using scanf to get char tempAnswer can not skip the space
// scanf("%c", &tempAnswer);
//using cin to get char tempAnswer can skip the space
cin >> tempAnswer;
tempQuestion.trueOptionsAndAnswer += tempAnswer;
if(i != tempTrueOptions - 1) {
tempQuestion.trueOptionsAndAnswer += " ";
}
}
tempQuestion.score = tempScore;
questions.push_back(tempQuestion);
}
getchar();
string student;
int scores[N];
for(int i = 0; i < N; i++) {
scores[i] = 0;
}
int countWrong[M];
for(int i = 0; i < M; i++) {
countWrong[i] = 0;
}
for(int i = 0; i < N; i++) {
getline(cin, student);
int index = 0;
for(int j = 0; j < student.length(); j++) {
if(student[j] == '(') {
j++;
string studentAnswer = "";
while(student[j] != ')') {
studentAnswer += student[j];
j++;
}
if(questions[index].trueOptionsAndAnswer.compare(studentAnswer) == 0) {
scores[i] += questions[index].score;
} else {
countWrong[index]++;
}
index++;
}
}
}
for(int i = 0; i < N; i++) {
printf("%d\n", scores[i]);
}
int maxWrong = 0;
for(int i = 0; i < M; i++) {
if(countWrong[i] > maxWrong) {
maxWrong = countWrong[i];
}
}
if(maxWrong == 0) {
cout << "Too simple" << endl;
} else {
cout << maxWrong;
for(int i = 0; i < M; i++) {
if(countWrong[i] == maxWrong){
cout << " " << (i + 1);
}
}
}
}
C++解题报告: