题目B1041 考试座位号
-
题意
根据给的映射关系查询座位号 -
思路
这里很明显就是一个映射,所以我自然的使用了map,但是这样增加了空间复杂度,因为这里座位不会重复然后是连续的,所以其实可以采用数组的下标作为映射的元素。 -
Code in C++
#include <iostream>
#include <string>
#include <map>
struct info {
std::string number;
int sit;
}student;
std::map<int, info> tables;
int main()
{
int N;
std::cin >> N;
while(N--) {
int pre_sit;
std::cin >> student.number >> pre_sit;
std::cin >> student.sit;
tables[pre_sit] = student;
}
int M;
std::cin >> M;
while(M--) {
int query;
std::cin >> query;
std::cout << tables[query].number << " " << tables[query].sit << std::endl;
}
return 0;
}
题目 B1004 成绩排名
-
题意
如题,输出成绩最高和最低学生的信息。 -
思路
这里想过几种思路,数组下标当作分数;sort排序[这个书里说会超时,但是我ac了。。。];最后就是在输入的时候直接比较记录max
,min
的值。这里给出第三种的代码。 -
Code in C++
#include <iostream>
struct info {
char name[11];
char number[11];
int grade;
}tmp, g_max, g_min;
int main()
{
int n;
std::cin >> n;
g_max.grade = -1;
g_min.grade = 101;
for(int i = 0; i < n; ++i) {
std::cin >> tmp.name >> tmp.number >> tmp.grade;
if (tmp.grade > g_max.grade) {
g_max = tmp;
}
if (tmp.grade < g_min.grade) {
g_min = tmp;
}
}
printf("%s %s\n", g_max.name, g_max.number);
printf("%s %s\n", g_min.name, g_min.number);
return 0;
}
题目 B1028 人口普查
-
题意
判断范围内,输出年纪的最大值和最小值信息。 -
思路
这里我直接使用字符串,因为日期格式是一定,对于字符串来说,年纪越大的字符串值越小,所以这里不管是和边界值还是判断记录最大值和最小值时都非常方便。
注意
:当都不在范围内时只输出0
. -
Code in C++
#include <iostream>
#include <sstream>
#include <string>
const std::string TODAY = "2014/09/06";
const std::string MAXDAY = "1814/09/06";
struct info{
std::string name;
std::string birthday;
}tmp, age_max, age_min;
bool isValid(const std::string &birth) {
// check
if (birth > TODAY || birth < MAXDAY) {
return false;
}
return true;
}
int main()
{
age_max.birthday = TODAY;
age_min.birthday = MAXDAY;
int N;
std::cin >> N;
int count = 0;
while(N--) {
std::cin >> tmp.name >> tmp.birthday;
if (isValid(tmp.birthday)) {
++count;
if (age_max.birthday >= tmp.birthday) {
age_max.name = tmp.name;
age_max.birthday = tmp.birthday;
}
if (age_min.birthday <= tmp.birthday) {
age_min.name = tmp.name;
age_min.birthday = tmp.birthday;
}
}
}
if (count == 0) {
std::cout << count << std::endl;
} else {
std::cout << count << " " << age_max.name << " " << age_min.name << std::endl;
}
return 0;
}
小结
- 做题前思路应该为,空间复杂度是否还能降?这些数据是否一定要保存下来还是只需要用临时值过渡下就可以。
- 对于数组下标的使用和map使用场景。
a. 两者都需要无重复
b. 数组适用于范围是连续的,map无所谓只要类型一致就好