Origin address: http://codeforces.com/gym/101652/attachments
Implication: Give a string containing only'B','R', let you find an interval in which the difference between the number of'R'and'B' is greatest.
Considering two situations, one is to determine the maximum difference in the case of more R than B. The other is the maximum difference in the case of more B than R. Then we can take a maximum value. As for judgment, we can sweep through O(n) to determine the maximum difference and the range of intervals.
Look at the code in detail
#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) {//Updating the range of intervals while updating the difference ans1 = sum; y1 = i; lx1 = x1; ly1 = y1; } } else { sum--;//If sum < 0, it means that the former can be discarded. 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; }