1 条题解
-
0
前缀和+数学优化
将一种颜色设为 另一种设为 构造一个新的数组,然后对这个数组做前缀和。那么只要前缀和中任选两个点的值相等就意味着这段区间两种宝石的数量相等。即 说明 这是个合法区间。
用桶数组保存第一次出现的数字,如果重复出现了找最大值即可。
#include <iostream> #include <cstring> #include <algorithm> #include<map> using namespace std; #define x first #define y second typedef long long LL; typedef pair<int, int> PII; const int N = 300010; int main() { string s; cin >> s; map<int,int> m; int x = 0, ans = 0; m[0] = 0; for(int i = 1; i <= s.size(); i ++) { if(s[i - 1] == 'G') x ++; else x --; if(m.count(x)) ans = max(ans, i - m[x]); else m[x] = i; } cout << ans << endl; return 0; }注意边界:枚举的区间
[l,r],在转化为前缀和之后应该是sum[r] - sum[l - 1],所以会初始化m[0] = 0。
- 1
信息
- ID
- 388
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 13
- 已通过
- 5
- 上传者