CodeForces 18C - Stripe 解题心得
原题:
Description
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains nspace-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Sample Input
9
1 5 -6 7 9 -16 0 -2 2
3
3
1 1 1
0
2
0 0
1
分析:从头到尾扫一次就行了,每扫一个累加前面所以项的和,再把判断2倍和是不是等于总和就可以了 ,复杂度为n
代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; int a[100000 + 10]; int t_left[100000 + 10]; int sum; int main() { int cnt = 0; int *p = a; int n; cin >> n; for (int i = 0; i < n; i++) { scanf("%d", a + i); if (i == 0) t_left[i] = a[i]; t_left[i] = t_left[i - 1] + a[i]; sum += a[i]; } for (int i = 0; i < n-1; i++) { if (2 * t_left[i] == sum) cnt++ ; } cout << cnt << endl; return 0; }