首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Codeforces中解决935B - Fafa和门

在Codeforces中解决935B - Fafa和门
EN

Stack Overflow用户
提问于 2021-07-31 15:31:09
回答 1查看 57关注 0票数 0

我有一个关于935B - Fafa和CodeForces的门的问题。我的代码对于第一个测试用例是有效的,但是它在测试用例20上卡住了,这是我使用的代码,有人能告诉我我哪里做错了吗?谢谢!

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-31 18:04:06

除了我在上面的评论中提到的i<=a问题之外,还有另一个问题。

即使您将for循环修复为在i<a之后停止,也可以使用以下语句:

代码语言:javascript
复制
if (x == y && s[i] == s[i+1]) total += 1;

仍将引用s[i+1]处的无效索引,因为i+1是数组最后一次迭代时的无效索引。

在循环的每一次迭代中,您需要首先查看他是否在gate,然后适当地更新xy,然后评估他是否更改了王国。

如果他在x > y的位置,你就知道他在较低的王国。同样,如果是y > x,你就知道他在地图上的上层王国。

我认为这更接近你想要的:

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68603478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档