代码源 #863.吃糖果
桌子上从左到右放着 n 个糖果。糖果从左到右编号,第 i 块糖果的重量为 wi。小明和小红要吃糖果。
小明从左边开始吃任意数量的糖果。(连续吃,不能跳过糖果)
小红从右边开始吃任意数量的糖果。(连续吃,不能跳过糖果)
当然,如果小明吃了某个糖果,小红就不能吃它(反之亦然)。
他们的目标是吃同样重量的糖果,请问此时他们总共最多能吃多少个糖果?
输入格式
第一行包含一个整数 n,表示桌上糖果的数量。
第二行包含 n 个整数 w1,w2,…,wn,表示糖果从左到右的重量。
输出格式
一个整数,表示小明和小红在满足条件的情况下总共可以吃的糖果的最大数量。
数据范围
1≤n≤2∗105,1≤wi≤104
输入样例
9
7 3 20 5 15 1 11 8 10
输出样例
7
题目大意:
大意为给出一个序列,求从左往右前缀和与从右往左前缀和相等时,最多可以选多少个数。
思路:
套个双指针模板就好了。
AC代码(带注释):
1 #include<algorithm> 2 #include<iomanip> 3 #include<stdio.h> 4 #include<cstdio> 5 #include<math.h> 6 #include<iostream> 7 #include<cstring> 8 #include<stack> 9 #include<queue> 10 #include<string.h> 11 #include<set> 12 #include<map> 13 14 using namespace std; 15 #define endl '\n' 16 #define ull unsigned long long 17 #define ll long long 18 #define ld long double 19 #define PII pair<int,int> 20 const int N = 2e5+7; 21 22 int n; 23 int w[N]; 24 25 int main() 26 { 27 //要是超时可能就是没加上这句话 28 ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); 29 cin >> n; 30 for (int i = 1; i <= n; i++) 31 { 32 cin >> w[i]; 33 } 34 int a = 0; //小明 35 int b = 0; //小红 36 int ans = 0; 37 for (int i = 1, j = n; i < j; i++)//双指针 38 { 39 a += w[i]; 40 while (a > b && i < j)//双指针判断语句 41 { 42 b += w[j]; j--; 43 } 44 if (a == b) 45 { 46 ans = i + n - j; 47 } 48 } 49 cout << ans; 50 return 0; 51 }