Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer ai written on it.
They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.
Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x−y|. Find the minimum possible value of|x−y|.
- 2≤N≤2×105
- −109≤ai≤109
- ai is an integer.
Input is given from Standard Input in the following format:
N a1 a2 … aN
Print the answer.
6 1 2 3 4 5 6
1
If Snuke takes four cards from the top, and Raccoon takes the remaining two cards,x=10, y=11, and thus |x−y|=1. This is the minimum possible value.
2 10 -10
20
Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=−10, and thus |x−y|=20.
这题题意给你一列数字,然后把这分为两堆,直接切断,每堆至少有一个元素,这列数字不能排序的,然后求得两部分的差的绝对值的最小值。
思路:直接暴力的求,从第一个数开始,输入每个值,就把这个值和之前的值之和加起来,单独放一个数组b[n]里面,由于−109≤ai≤109,所以b[n]得long long 类型,然后同时把输入的值的总和求出来,然后就遍历一遍,不断的更新最小值。最后就能得到min了。
#include<iostream>
#include<cmath>
using namespace std;
long long a[200005];
long long b[200005];
int main()
{
int n;
cin >> n;
long long sum = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
if (i == 0)
b[i] = a[i];
else
b[i] = b[i - 1] + a[i];
sum = sum + a[i];
}
long long min;
if (b[0] > sum - b[0])
min = 2 * b[0] - sum;
else
min = sum - (2 * b[0]);
for (int i = 1; i < (n - 1); i++)
{
if (min > abs(sum - (2 * b[i])))
min = abs(sum - (2 * b[i]));
}
cout << min << endl;
return 0;
}