c++ - 解决 935B - Fafa 和 Codeforces 中的大门
问题描述
我有一个关于 CodeForces 中的 935B - Fafa 和 Gates 的问题。我的代码适用于第一个测试用例,但它卡在测试用例 20 上,这是我使用的代码,有人可以告诉我我在这里做错了什么吗?谢谢!
#include <iostream>
#include <string>
using namespace std;
int main(){
long long a, x = 0, y = 0, total = 0;
cin >> a;
string s;
cin >> s;
for (long long i = 0; i <= a; i++){
if (s[i] == 'U') x += 1;
if (s[i] == 'R') y += 1;
if (x == y && s[i] == s[i+1]) total += 1;
}
cout << total << endl;
}
解决方案
除了i<=a
我在上面的评论中提到的问题之外,还有另一个问题。
即使您将 for 循环修复为在 之后停止i<a
,那么此语句:
if (x == y && s[i] == s[i+1]) total += 1;
仍将引用无效索引,s[i+1]
因为i+1
在数组的最后一次迭代中是无效索引。
在循环的每次迭代中,您需要先查看他是否在门口,然后更新x
或y
适当地更新,然后评估他是否改变了王国。
如果他在一个位置x > y
,你就知道他在下界。同样,如果y > x
,您知道他在地图上的上层王国。
我认为这更接近你想要的:
bool topKingdom = false; // initially at 0,0. Fafa is currently in the "lower kingdom" on the map
for (long long i = 0; i < a; i++){
bool atGate = (x == y);
if (s[i] == 'U') y++;
if (s[i] == 'R') x++;
// if we were previously "at a gate", assess if we are now in a new kingdom from before
if (atGate && !topKingdom && y > x) {
topKingdom = true;
total++;
}
else if (atGate && topKingdom && x > y) {
topKingdom = false;
total++;
}
}
cout << total << endl;
推荐阅读
- javascript - 更新 Firestore 文档时可以动态更改键和值吗?
- django - 在 Elastic Beanstalk 上运行集中式服务
- css - 在横向模式下在移动视图中显示/隐藏 div
- javascript - Swiper,无法使图库拇指移动如何解决?
- r - 如何使用 tidyverse 去除基于标准开发的异常值?
- laravel - 使用 laravel 修改 vuetify 主题
- java - 如何使用 Java 读取电子邮件中的徽标和图像,其中电子邮件的内容是 html/纯文本
- c# - 如何在 dot net 的 confluent kafka 中将消费方法设为非阻塞
- php - Laravel 经纬度最近的城市
- python - 在哪里运行在线 Python 3.8 脚本