目录
一、基础语法题目
1.1 成绩排序(稳定排序、多关键字排序)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
struct Student {
string name;
int score, id;
bool operator<(const Student &S) const {
if (score != S.score) return score < S.score;
else return id < S.id;
}
bool operator>(const Student &S) const {
if (score != S.score) return score > S.score;
else return id < S.id;
}
} student[N];
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> student[i].name >> student[i].score;
student[i].id = i;
}
if (!m) sort(student, student + n, greater<Student>()); // 从大到小排序
else sort(student, student + n);
for (int i = 0; i < n; i++)
cout << student[i].name << " " << student[i].score << endl;
return 0;
}
c++ 自带的稳定排序
stable_sort()
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
struct Stu {
string name;
int score;
bool operator<(const Stu &s) const {
return score < s.score;
}
bool operator>(const Stu &s) const {
return score > s.score;
}
} stu[N];
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> stu[i].name >> stu[i].score;
if (!m) stable_sort(stu, stu + n, greater<Stu>());
else stable_sort(stu, stu + n);
for (int i = 0; i < n; i++)
cout << stu[i].name << " " << stu[i].score << endl;
return 0;
}
1.2 时间计算类题目
重要函数
const int month[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断是否为闰年,闰年返回1,平年返回0
int is_leap(int year) {
if (year % 4 == 0 && year % 100 || year % 400 == 0) return 1;
return 0;
}
// y年m月有多少天
int get_days(int y, int m) {
if (m == 2) return month[2] + is_leap(y);
return month[m];
}
// 从今年这一天到明天这一天所经过的天数
int get_year_day(int y, int m) {
if (m <= 2) return 365 + is_leap(y); // 判断今年是否为闰年
return 365 + is_leap(y + 1); // 判断明年是否为闰年
}
1.2.1 打印日期
#include <iostream>
#include <algorithm>
using namespace std;
const int month[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int is_leap(int year) {
if (year % 4 == 0 && year % 100 || year % 400 == 0) return 1;
return 0;
}
int get_days(int y, int m) {
if (m == 2) return month[2] + is_leap(y);
return month[m];
}
int main() {
int y, s;
while (cin >> y >> s) {
int m = 1, d = 1;
s--;
while (s--)
if (++d > get_days(y, m)) {
d = 1; // 重置每月第一天
if (++m > 12) m = 1, y++; // 重置每年第一天
}
printf("%04d-%02d-%02d\n", y, m, d);
}
return 0;
}
1.2.2 日期累加
#include <iostream>