USACO 2021 December Contest, Bronze 官方题解

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值