Problem 1. Lonely Photo
(Analysis by Nick Wu)
We need to count the number of substrings of length 3 that contain exactly one G or one H.
The most direct solution involves checking every substring of length at least 3. There are O(N^2) such substrings to check, and each one takes O(N) time to validate, for a total runtime of O(N^3).
To improve the performance of this solution, we can choose to check substrings in a specific order. In particular, fix the leftmost character in the substring and then start scanning to the right. If we have seen at least three characters and exactly one of them is G or one of them is H, increment a counter. Loop over all leftmost characters and then print the counter at the end. The approach of this solution is O(N^2).
#include <iostream>
#include <string>
int main() {
int n;
std::string s;
std::cin >> n >> s;
int ans = 0;
for(int i = 0; i < (int)s.size(); i++) {
int g = 0;
int h = 0;
for(int j = i; j < (int)s.size(); j++) {
if(s[j] == 'G') g++;
else h++;
if(g+h >= 3 && (g==1 || h==1)) ans++;
}
}
std::cout << ans << "\n";
}
It is possible to solve this problem in O(N). For each character, let's count the number of photos in which that character is the odd one out. In the case where that chara

本文提供了USACO 2021十二月比赛青铜组的官方题解,包括两道题目。第一题Lonely Photo讨论了如何高效地计算字符串中长度为3的子串中恰好含有一个G或一个H的数量,提出了一种O(N^2)的解决方案和一个O(N)的优化方法。第二题Air Cownditioning讨论如何调整温度序列,使得所有牛都满意,给出了一种逐步调整的策略,并证明了解决问题的公式可以在O(N)时间内计算。
最低0.47元/天 解锁文章
1303

被折叠的 条评论
为什么被折叠?



