CF - F. Eating Candies
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<vector>
#include<cmath>
#include<climits>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
long long a[N], b[N], c[N];
int main() {
int t;
cin >> t;
while (t --) {
int n;
cin >> n;
for(int i = 1; i <= n; i ++)cin >> a[i];
c[n] = a[n];
b[1] = a[1];
for(int i = 2; i <= n; i ++)b[i] = a[i] + b[i - 1];
for(int i = n - 1; i >= 1; i --)c[i] = c[i + 1] + a[i];
long long mx = 0, mi = 0;
for(int i = 1; i <= n; i ++)
{
int l = 1, r = n;
while(l < r)
{
int m = (l + r + 1) / 2;
if(c[m] >= b[i] )l = m;
else r = m - 1;
}
if(c[l] == b[i])
{
if(l > i)
{
mi = i;
mx = n - l + 1;
}
}
}
cout << mx + mi <<endl;
}
return 0;
}
因为前缀和数组边界问题wrong了3发,hh,真***,附上错误代码
#include<cstring>
#include<string>
#include<iostream>
#include<vector>
#include<cmath>
#include<climits>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
long long a[N], b[N], c[N];
int main() {
int t;
cin >> t;
while (t --) {
int n;
cin >> n;
for(int i = 1; i <= n; i ++)cin >> a[i];
for(int i = 1; i <= n; i ++)b[i] = a[i] + b[i - 1];
for(int i = n; i >= 1; i --)c[i] = c[i + 1] + a[i];
long long mx = 0, mi = 0;
for(int i = 1; i <= n; i ++)
{
int l = 1, r = n;
while(l < r)
{
int m = (l + r) / 2;
if(c[m] <= b[i] )r = m;
else l = m + 1;
}
if(c[l] == b[i])
{
if(l > i)
{
mi = i;
mx = n - l + 1;
}
}
}
cout << mx + mi <<endl;
}
return 0;
}