P1114 “非常男女”计划
分析:用两个前缀和数组统计男女的前缀和,再统计区间和,如果出现两个x(区间和)就求最大值
#include<bits/stdc++.h>
using namespace std;
int n,a[1000005],s1[1000005],s0[1000005],ans;
map<int,int> mp;
int main(){
cin>>n;
for(int i = 1;i <= n;i++){
cin >> a[i];
if(a[i] == 1){
s1[i] = s1[i - 1] + 1;//男生前缀和
s0[i] = s0[i - 1];
}else{
s1[i] = s1[i - 1];//女生前缀和
s0[i] = s0[i - 1] + 1;
}
}
for(int i = 0;i <= n;i++){
int x = s1[i] - s0[i];
if(mp.count(x) == 1){//说明有两个x
ans = max(ans,i - mp[x]);
}
else mp[x] = i;//没有出现呢x
}
cout << ans;
return 0;
}D - CF1006C Three Parts of the Array
分析:先求a的前缀和s1,再求b的前缀和s2,再用二分找到s1s2相等的位置即可
#include<bits/stdc++.h>
using namespace std;
long long n;
long long a[200005],b[200005];
long long s1[200005],s2[200005];
int main(){
cin >> n;
for(int i = 1;i <= n;i++){
cin >> a[i];
s1[i] = s1[i - 1] + a[i];//前缀和
}
for(int i = n;i >= 1;i--){
s2[n - i + 1] = s2[n - i] + a[i];//后缀和
}
for(int i = n - 1;i >= 1;i--){
//int l = -1,r = n + 1;
// while(l + 1 < r){
int pos = lower_bound(s2 + 1,s2 + n + 1,s1[i]) - s2;//二分查找s2第一次出现的等于s1的位置
if(i + pos <= n and s2[pos] == s1[i]){//两个前缀的长度和<=n
cout << s2[pos];
return 0;
}
//}
}
cout << 0;
return 0;
}
作业 P2697 宝石串
#include<bits/stdc++.h>
using namespace std;
int n,s1[1000005],s0[1000005],ans;
int a[1000005];
string s;
map<int,int> mp;
int main(){
cin>>s;
int n = s.size();
s = '@' + s;
for(int i = 1;i <= n;i++){
if(s[i] == 'R'){
s1[i] = s1[i - 1] + 1;
s0[i] = s0[i - 1];
}else{
s1[i] = s1[i - 1];
s0[i] = s0[i - 1] + 1;
}
}
for(int i = 0;i <= n;i++){
int x = s1[i] - s0[i];
if(mp.count(x) == 1){
ans = max(ans,i - mp[x]);
}
else mp[x] = i;
}
cout << ans;
return 0;
}
P6625
#include<bits/stdc++.h>
using namespace std;
long long a[100005],s[100005];
long long n,max1 = 0,sum;
int main(){
cin >> n;
for(int i = 1;i <= n;i++){
cin >> a[i];
s[i] = s[i - 1] + a[i];
}
for(int i =1;i <= n;i++){
if(s[i] > 0 and i != 1) sum += s[i];
}
cout << sum;
return 0;
}
B4038 [GESP202409 三级] 平衡序列
#include<bits/stdc++.h>
using namespace std;
int t,n;
int a[10005],s[10005];
int main(){
cin >> t;
while(t--){
cin >> n;
bool f = false;
for(int i = 1;i <= n;i++){
cin >> a[i];
s[i] = s[i - 1] + a[i];
}
for(int i = 2;i <= n;i++){
if(s[i] == s[n] - s[i]) {
cout << "Yes" << '\n';
f = 1;
break;
}
}
if(f == false) cout << "No" <<'\n';
}
return 0;
}