粤港澳编程题
1 糖果
(1)考点:列表,循环
(2)思路
(3)参考答案
n = int(input()) # 4
a = list(map(int, input().split())) # 2 5 4 7
marked = [] #记录被标记的袋子
for i in range(n):marked.append(False)# Step 1: 标记比相邻都多的袋子
for i in range(n):# 处理左邻居if i > 0:left = a[i-1]else:left = a[n-1] # 环形数组,第一个元素的左邻居是最后一个元素# 处理右邻居if i < n-1:right = a[i+1]else:right = a[0] # 环形数组,最后一个元素的右邻居是第一个元素if a[i] > left and a[i] > right:marked[i] = True# print(marked) # [False, True, False, True]total_eaten = 0 #吃掉的糖果数
bucket = 0 # 桶里的糖果数
new_a = a.copy() # 新袋子的糖果数# Step 2: 处理被标记的袋子
for i in range(n):if marked[i]:half = a[i] // 2total_eaten += halfremaining = a[i] - halfbucket += remainingnew_a[i] = 0 # 先设置为0,因为之后会重新分配else:new_a[i] = a[i]# print(new_a) # [2, 0, 4, 0]# Step 3: 重新分配桶里的糖果
if bucket > 0:per_bag = bucket // nremainder = bucket % ntotal_eaten += remainderfor i in range(n):new_a[i] += per_bag# Step 4: 找出最大值
max_candies = max(new_a)print(total_eaten, max_candies)
C++代码:
#include <iostream>
#include <vector>using namespace std;int main() {int n;cin >> n;vector<int> a(n);for (int i = 0; i < n; ++i) {cin >> a[i];}vector<bool> marked(n, false);// Step 1: 标记比相邻都多的袋子for (int i = 0; i < n; ++i) {// 处理左邻居int left = (i > 0) ? a[i-1] : a[n-1];// 处理右邻居int right = (i < n-1) ? a[i+1] : a[0];if (a[i] > left && a[i] > right) {marked[i] = true;}}int total_eaten = 0; // 吃掉的糖果数int bucket = 0; // 桶里的糖果数vector<int> new_a = a; // 新袋子的糖果数// Step 2: 处理被标记的袋子for (int i = 0; i < n; ++i) {if (marked[i]) {int half = a[i] / 2;total_eaten += half;int remaining = a[i] - half;bucket += remaining;new_a[i] = 0; // 先设置为0,因为之后会重新分配} else {new_a[i] = a[i];}}// Step 3: 重新分配桶里的糖果if (bucket > 0) {int per_bag = bucket / n;int remainder = bucket % n;total_eaten += remainder;for (int i = 0; i < n; ++i) {new_a[i] += per_bag;}}// Step 4: 手动查找最大值int max_candies = new_a[0]; // 假设第一个元素是最大值for (int i = 1; i < n; ++i) {if (new_a[i] > max_candies) {max_candies = new_a[i];}}cout << total_eaten << " " << max_candies << endl;return 0;
}
2 字符串
(1)考点:字符串,字典,循环嵌套
(2)思路
(3)参考答案
s = input() #'abcdbca'
n = len(s) #7
count = 0for i in range(n):freq = {} # 用字典记录字母出现次数for j in range(i, n):# 检查相邻字母是否相同if j > i and s[j] == s[j - 1]:break # 不满足条件3,直接跳出循环# 更新字母频率if s[j] not in freq:freq[s[j]] = 1else:freq[s[j]] +=1# 检查字母出现次数是否超过3if freq[s[j]] > 3:break # 不满足条件2,直接跳出循环# 检查子串长度是否为奇数if (j - i + 1) % 2 == 1:count += 1print(count)
C++:
#include <iostream>
#include <vector>
#include <string>using namespace std;int main() {string s;cin >> s;int n = s.length();int count = 0;for (int i = 0; i < n; ++i) {vector<int> freq(26, 0); // 记录字母出现频率for (int j = i; j < n; ++j) {// 检查相邻字母是否相同if (j > i && s[j] == s[j - 1]) {break; // 不满足条件3,直接跳出内层循环}// 更新频率freq[s[j] - 'a'] += 1;// 检查频率是否超过3if (freq[s[j] - 'a'] > 3) {break; // 不满足条件2,直接跳出内层循环}// 检查长度是否为奇数if ((j - i + 1) % 2 == 1) {count += 1;}}}cout << count << endl;return 0;
}