Gym - 101652S E - Purple Rain (贪心)

原题地址:http://codeforces.com/gym/101652/attachments

题意:给出一串只包含'B','R'的字符串,让你找出一段区间使得在这段区间里面'R'和'B'的数量之差最大.

思路;分两种情况考虑,一种是确定R比B多的情况下的最大差值.一种是B比R多的情况下的最大差值.然后取一个最值.至于判断,我们可以进行O(n)的扫一遍,确定最大差值以及区间范围.

具体看代码

#include <bits/stdc++.h>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define CLR(x,y) memset((x),y,sizeof(x))
#define fuck(x) cerr << #x << "=" << x << endl

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e5 + 5;
const int mod = 998244353;
char a[maxn];
int x1, x2, y1, y2;
int main() {
    scanf("%s", a + 1);
    int n = strlen(a + 1);
    int ans1 = 0, ans2 = 0;
    int sum = 0;
    x1 = 1, y1 = 1, x2 = 1, y2 = 1;
    int lx1, lx2, ly1, ly2;
    for (int i = 1; i <= n; i++) {
        if (a[i] == 'R') {
            sum++;
            if (sum > ans1) {//更新差值的同时更新区间范围
                ans1 = sum;
                y1 = i;
                lx1 = x1;
                ly1 = y1;
            }
        } else {
            sum--;//如果sum<0,就说明前面的可以舍去了
            if (sum < 0) {
                x1 = i + 1;
                sum = 0;
            }
        }
    }
    sum = 0;
    for (int i = 1; i <= n; i++) {
        if (a[i] == 'B') {
            sum++;
            if (sum > ans2) {
                ans2 = sum;
                y2 = i;
                lx2 = x2;
                ly2 = y2;
            }
        } else {
            sum--;
            if (sum < 0) {
                x2 = i + 1;
                sum = 0;
            }
        }
    }
    if (ans1 == ans2) {
        if (lx1 < lx2) printf("%d %d\n", lx1, ly1);
        else if (lx1 > lx2) printf("%d %d\n", lx2, ly2);
        else {
            if (ly1 < ly2) printf("%d %d\n", lx1, ly1);
            else printf("%d %d\n", lx2, ly2);
        }
    } else if (ans1 > ans2) printf("%d %d\n", lx1, ly1);
    else printf("%d %d\n", lx2, ly2);
    return 0;
}


猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/81748145