B - Splitting Pile

Problem Statement

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 |xy|. Find the minimum possible value of|xy|.

Constraints

  • 2N2×105
  • −109ai109
  • ai is an integer.
Input

Input is given from Standard Input in the following format:

N
a1 a2  aN
Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6
Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards,x=10y=11, and thus |xy|=1. This is the minimum possible value.

Sample Input 2

2
10 -10
Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10y=−10, and thus |xy|=20.



这题题意给你一列数字,然后把这分为两堆,直接切断,每堆至少有一个元素,这列数字不能排序的,然后求得两部分的差的绝对值的最小值。

思路:直接暴力的求,从第一个数开始,输入每个值,就把这个值和之前的值之和加起来,单独放一个数组b[n]里面,由于−109ai109,所以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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值