Codeforces 935B 暴力

传送门:题目

题意:

一个人只在平面第一象限运动,他只会往上走和往右走,每次直走一格距离,问穿过y=x这条线的次数,注意是穿过,如果只碰了一下,然后又回来则不算,

题解:

题目很简单,代码也很短,比赛的时候写复杂了,这里记录一下较为简单的解法:
比赛的时候想的是for循环模拟走,xy数组记录足迹,如果碰到y=x,标记一下,然后继续走,如果由标记,判断本次的点和上上次的中点,是不是在y=x上,用到了延后性思想。

赛后看题解,发现一个更简单的解法:
因为只有上走和右走,所以穿过y=x的走法只有上上和右右,这样写起来就非常简单了。

AC代码:(两份)

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e5 + 10;

int x[maxn], y[maxn];
int main(void) {
    x[0] = 0;
    y[0] = 0;
    bool flag = false;
    int n, ans = 0;
    char str[maxn];
    cin >> n;
    scanf("%s", str + 1);
    for (int i = 1; i <= n; i++) {
        if (str[i] == 'U')
            x[i] = x[i - 1], y[i] = y[i - 1] + 1;
        if (str[i] == 'R')
            x[i] = x[i - 1] + 1, y[i] = y[i - 1];

        if (flag == true) {
            flag = false;
            if ((x[i - 2] + x[i]) / 2 == (y[i - 2] + y[i]) / 2 && (x[i - 2] + x[i]) % 2 == 0 && (y[i - 2] + y[i]) % 2 == 0)
                ans++;
        }
        if (x[i] == y[i] && i != n)
            flag = true;
    }
    cout << ans << endl;
    return 0;
}
#include <iostream>
using namespace std;
int main () {
    int n = 0, ans = 0, x = 0, y = 0;
    string s;
    cin >> n >> s;
    for (int i = 0; i < n - 1; i++) {
        if (s[i] == 'R') 
            x++;
        else 
            y++;
        if (s[i] == s[i + 1] && x == y) 
            ans++;
    }
    cout << ans;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/81836396
今日推荐