Purple Rain
Purple rain falls in the magic kingdom of Linearland which is a straight, thin peninsula.
On close observation however, Professor Nelson Rogers finds that the purple rain is actually a mix of red and blue raindrops.
In his zeal, he records the location and color of the raindrops in different locations along the peninsula. Looking at the data, Professor Rogers wants to know which part of Linearland had the “least” purple rain.
After some thought, he decides to model this problem as follows. Divide the peninsula into n sections and number them west to east from 1 to n. Then, describe the raindrops as a sequence of R and B, depending on whether the rainfall in each section is primarily red or blue. Finally, find a subsequence of contiguous sections where the difference between the number of R and the number of B is maximized.
The input consists of a single line containing a string of n characters (1 ≤ n ≤ 105), describing the color of the raindrops in sections 1 to n.
It is guaranteed that the string consists of uppercase ASCII letters ‘R’ and ‘B’ only.
Print, on a single line, two space-separated integers that describe the starting and ending positions of the part of Linearland that had the least purple rain. These two numbers should describe an inclusive range; both numbers you print describe sections included in the range.
If there are multiple possible answers, print the one that has the westernmost starting section. If there are multiple answers with the same westernmost starting section, print the one with the westernmost ending section.
题意:给你一个字符串 ,只包含 R,B,问在哪个区间,R和 B 的数量差距最大。 如有多个答案,打印起点小的,若起点都相同还有多个答案,打印终点小的。。。
思路:哇,这个题,简直和 HDU 1003,毫无区别,最后几分钟才反应过来。。。。QAQ
可能我比较蠢,跑了两边 O(n), 就先假设 R 的值是1,B的值是 -1, 跑一边 连续子序列最大和, 然后反过来, R 为 -1,B 为 1,再跑一次。
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define cas(t) int t; scanf("%d",&t);
const int maxn = 1e6 + 10;
int a[maxn];
int sz;
void maxs(int &beg,int &en,int &maxsum){
int now,p;
beg = en = p = 1;
now = maxsum = a[1];
for(int i = 2;i <= sz;i ++){
if(now + a[i] < a[i]){
now = a[i];
p = i;
}
else {
now += a[i];
}
if(maxsum < now){
maxsum = now;
beg = p;
en = i;
}
}
}
int main()
{
string s;
while(cin >> s){
sz = 0;
for(int i = 0;i < s.size();i ++){
if(s[i] == 'R') a[++sz] = 1;
else a[++ sz] = -1;
}
int beg,en,maxsum;
maxs(beg,en,maxsum);
sz = 0;
for(int i = 0;i < s.size();i ++){
if(s[i] == 'B') a[++ sz] = 1;
else a[++ sz] = -1;
}
int beg1,en1,maxsum1;
maxs(beg1,en1,maxsum1);
if(maxsum < maxsum1)
printf("%d %d\n",beg1,en1);
else if(maxsum == maxsum1){
if(beg1 < beg) printf("%d %d\n",beg1,en1);
else if(beg1 == beg)
printf("%d %d\n",beg1,min(en,en1));
else printf("%d %d\n",beg,en);
}
else printf("%d %d\n",beg,en);
}
return 0;
}