【APCS】2025年1月實作題 C++ 解題筆記(前兩題)

本篇筆記紀錄個人解題過程,內容僅供參考。

  1. 等紅綠燈:https://zerojudge.tw/ShowProblem?problemid=q181

tag : 資料處理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>

using namespace std;

int main(){
int a, b;
cin >> a >> b;
int n;
cin >> n;
int sum;
for (int i = 0; i < n; i++){
int wait_time = 0;
cin >> wait_time;
if (wait_time % (a+b) >= a){
sum += abs((wait_time % (a+b) - b) - a);
}
}
cout << sum;
return 0;
}

image

  1. 字串操作:https://zerojudge.tw/ShowProblem?problemid=q182

tag : 字串處理

因為題目保證字串都是偶數,所以並不會很難。

需要設計三種函數:

  1. 字串兩兩交換
  2. 兩兩排序
  3. 完美重排

前兩個字串操作都是需要把字串都分組成兩個字元。

完美重排則是直接將字串拆半就好。

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <bits/stdc++.h>

using namespace std;

string swapstr(const string& input);

string sortstr(const string& input);

string mixstr(const string& input);

int main(){
string s1;
getline(cin, s1);
int k;
cin >> k;
for (int i = 0;i < k;i++){
int state = -1;
cin >> state;
if (state == 0){
s1 = swapstr(s1);
}
else if (state == 1){
s1 = sortstr(s1);
}
else{
s1 = mixstr(s1);
}
}
cout << s1;
return 0;
}

string swapstr(const string& input){
string result = input;
for (size_t i = 0; i < result.length(); i+=2){
swap(result[i], result[i+1]);
}
return result;
}

string sortstr(const string& input){
string result = input;
for (size_t i = 0; i < result.length(); i+=2){
if (result[i] > result[i+1]){
swap(result[i], result[i+1]);
}
}
return result;
}

string mixstr(const string& input){
int n = input.length();
string first = input.substr(0, n/2);
string second = input.substr(n/2);

string result;
result.reserve(n);

for (int i = 0; i < n / 2; ++i){
result += first[i];
result += second[i];
}
return result;
}

image

3、4 題對我來說還是難到靠腰,所以先說不了。