ACM寒假第一讲

一、Long Loong

设计思路

题目要求输入一个数字N,输出一个字母L,N个字母o,一个字母n,一个字母g,这边想到直接使用for循环,执行N次操作即可。(毕竟是easy题不需要什么高端操作)

设计代码

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;//输入数字N
cout << "L";//先输出L
for (int i = 0; i < n; i++) {//for循环执行次数输出o
cout << "o";
}
cout << "ng";//ng一起输出
return 0;
}

二、YES or YES ?

设计思路

题目要求设计一个程序,检测其是否为“YES”,并且”YES”不分大小写。刚开始的时候想直接用穷举进行判断,毕竟“YES”部分大小写最多也就八种可能性,也不会很困难;后来继续思考有没有更优的思路,翻找C++的库得知有一个小写转大写的函数,于是有一个新思路,利用函数将输入的字符串转为大写,之后直接与“YES”作比较即可,较为省事,代码也比较简洁。

设计代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
string s;
getline(cin, s);//字符串输入
transform(s.begin(), s.end(), s.begin(), ::toupper);//利用transform函数转换为大写
if (s == "YES") {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}

return 0;
}

三、Problem Generator

设计思路

题目简单来说,要求m轮比赛中,每一轮比赛都必须至少有ABCDEFG七个类型的题目各一个,因此共需求m个对应字母。由于ABCDEFG七个大写字母都是char类型,因此这边的思路是:先写一个char为key,int为value的map类型,由于存储每一次输入的题目的各类型个数,之后再从A到G进行遍历,检测差值并相加即可

设计代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main() {
map<char, int>problemScale = {{'A', 0}, {'B', 0}, {'C', 0}, {'D', 0}, {'E', 0}, {'F', 0}, {'G', 0}};//map类型检索
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
string a;
cin >> a;
cin.ignore();
for (int i = 0; i < a.size(); i++) {
char x = a[i];
problemScale[x]++;//对应字母次数加
}
int count = 0;
int x = 0;
for (int i = 'A'; i <= 'G'; i++) {
if (problemScale[i] < m) {
x = m - problemScale[i];//差值
count += x;
}
problemScale[i] = 0;
}
cout << count << endl;
}
return 0;
}

四、rules

设计思路

这个题目主要要考虑“大于等于一半的人”以及“大于等于一半的天数”这两个语境,其实不能用简单的整除来表示,必须用double类型算出精确小数(如果是奇数的话),之后再进行向上取整即可。具体统计过程其实利用数组(毕竟只有1000个居民)统计和int计数器即可。

设计代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cmath>
using namespace std;

int main() {
int n, m;
long long int k;
cin >> n >> m >> k;
int t = m;//备份,以便后续比较
int next = 0;//计天数
while (m--) {
int count = 0;//计人数
int a[1000] = {0};
for (int i = 0; i < n; i++) {
cin >> a[i];//输入居民遵守的规则
}
for (int i = 0; i < n; i++) {
if (a[i] == k) {
count++;
}
}
if (count >= ceil((double)n / 2)) {//向上取整
next++;
}
}
if (next >= ceil((double)t / 2)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}

五、学习总结

在这次C++代码中,进一步学会了对STL的运用以及对算法的初步认识,而关于语法糖中的一些便捷的用法还没有完全掌握,期待后续进一步的掌握来提升代码质量。


ACM寒假第一讲
https://gaster44.github.io/2025/01/22/ACM寒假第一讲/
作者
huangjinhong
发布于
2025年1月22日
许可协议