jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#include<stdio.h>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
 
 
using namespace std;
 
//conversion
//------------------------------------------
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
 
//math
//-------------------------------------------
template<class T> inline T sqr(T x) {return x*x;}
 
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
 
//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
 
//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
 
//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);
 
//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))
 
//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

//pair sort
bool compare_by_b(pair<LL, LL> a, pair<LL, LL> b) {
    if(a.second != b.second){
        return a.second < b.second;
    }else{
        return a.first < b.first;
    }
}


void solve(long long N, std::string S){
    VI w(N);
    VI b(N);
    int wcnt=0;
    int bcnt=0;
    REP(i, N){
        if(S[i]=='#')bcnt++;
        if(S[N-i-1]=='.')wcnt++;
        w[N-i-1]=wcnt;
        b[i]=bcnt;
    }
    int ans=600000;
    REP(i,N-1){
        debug(b[i])
        debug(w[i+1])
        ans=min(ans,b[i]+w[i+1]);
    }
    ans=min(ans,bcnt);
    ans=min(ans,wcnt);
    if(bcnt==0 || wcnt==0){cout<<0<<endl;}
    else cout<<max(0,ans)<<endl;
    
}

int main(){
    long long N;
    scanf("%lld",&N);
    std::string S;
    std::cin >> S;
    solve(N, S);
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
	int n;
	cin >> n;
	string s;
	cin >> s;
	//cleaning
	while (true) {
		if (s.length()>=2&&s.at(0) == '.')s = s.substr(1);
		else if (s.length() == 1) {
			cout << 0 << endl;
			return 0;
		}
		else break;
	}
	while (true) {
		if (s.length() >= 2 && s.at(s.length() - 1) == '#')s = s.substr(0, s.length() - 1);
		else if (s.length() == 1) {
			cout << 0 << endl;
			return 0;
		}
		else break;
	}
	//cout << s << endl;
	vector<vector<int>>bw(0, vector<int>(2));
	int b = 0;
	int w = 0;
	for (int i = s.length() - 1; i >= 0; i--) {
		if (b == 0 && s.at(i) == '.')w++;
		else if (b >= 1 && s.at(i) == '.') {
			bw.push_back({ b,w });
			b = 0;
			w++;
		}
		else b++;
	}
	bw.push_back({ b,w });
	/*for (int i = 0; i < bw.size(); i++) {
		for (int j = 0; j < 2; j++)cout << " " << bw.at(i).at(j);
		cout << endl;
	}*/
	reverse(bw.begin(), bw.end());
	ll ans = 10000000;
	ll blcnt = 0;
	for (int i = 0; i < bw.size(); i++) {
		if (i == 0) {
			ans = bw.at(i).at(1);
			blcnt += bw.at(i).at(0);
		}
		else {
			ans = min(ans, blcnt + bw.at(i).at(1));
			blcnt += bw.at(i).at(0);
		}
	}
	ans = min(ans, blcnt);
	cout << ans << endl;

}
//  [c]
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
int MIN(int a,int b){
    return a<b?a:b;
}
int compare(const void *a,const void *b){
    if(*(int *)a>*(int *)b)return 1;
    return -1;
}
int main()
{   int n,b[200001]={0},i,w[200001]={0};
    scanf("%d",&n);
    
    char s[n+1];
    int chk=0;
    scanf("%s",s);
    for(i=0;i<n;i++){
        if(s[i]=='.'){
            chk++;
        }
    }
    if(chk==0||chk==n){
        printf("0");
        return 0;
    }
    if(s[0]=='#'){
        w[0]=chk;
        b[0]=1;
    }else{
        w[0]=chk-1;
    }
    for(i=1;i<n;i++){
        if(s[i]=='#'){
            b[i]=b[i-1]+1;
            w[i]=w[i-1];
        }else{
            b[i]=b[i-1];
            w[i]=w[i-1]-1;
        }
    }
    int x=11451419;
    int ans[200001]={0};
    for(i=0;i<n;i++){
        if(b[i]==i+1&&w[i]==n-(i+1)){
          x=chk;  
        }
        ans[i]=b[i]+w[i];
    }
    qsort(ans,n,sizeof(int),compare);
    printf("%d",MIN(ans[0],x));
    return 0;
}
//  [c]
#include <stdio.h>

int N;
char S[271828];

int asumi[271828], iguti[271828];

int main(void) {
	int i;
	int hayamisaori;
	if (scanf("%d", &N) != 1) return 1;
	if (scanf("%271826s", S + 1) != 1) return 1;
	for (i = 1; i <= N; i++) {
		asumi[i] = asumi[i - 1] + (S[i] == '#');
	}
	for (i = N; i >= 1; i--) {
		iguti[i] = iguti[i + 1] + (S[i] == '.');
	}
	hayamisaori = N;
	for (i = 0; i <= N; i++) {
		int hanazawakana = asumi[i] + iguti[i + 1];
		if (hanazawakana < hayamisaori) hayamisaori = hanazawakana;
	}
	printf("%d\n", hayamisaori);
	return 0;
}

/* 白(0個以上) → 黒(0個以上) にする */
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

int
main(void)
{
        int N;
        char *stone;
        int result = INT_MAX;
        int black = 0;
        int white = 0;

        scanf("%d\n", &N);
        stone = malloc(N);
        memset(stone, 0, sizeof(char) * N);

        for (int i = 0; i < N; i++) {
                char c;
                scanf("%c", &c);

                if (c == '.')
                        white++;
                else
                        stone[i] = 1;
        }

        for (int i = 0; i <= N; i++) {
                if(white + black < result)
                        result = white + black;

                if (i == N)
                        break;

                if (stone[i] == 1)
                        black++;
                else
                        white--;
        }

        printf("%d", result);

        return 0;
}
//  [javascript]
"use strict";
function Main(input) {
    let cin = new Inputer(input);
    let N = cin.getInt(), S = cin.getStr();
    let W = new Array(N + 1).fill(0);
    for (let n = 0; n < N; n++)
        W[n + 1] = W[n] + (S.charAt(n) == '#' ? 1 : 0);
    let ans = Number.MAX_SAFE_INTEGER;
    for (let n = 0; n <= N; n++)
        ans = Math.min(ans, W[n] + N - n - (W[N] - W[n]));
    console.log(ans);
}
class Inputer{constructor(t){this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	n := oneInt()
	s := oneStr()

	ans := calc(s, n)
	fmt.Println(ans)
}

func calc(s string, n int) int {
	currentDot := 0
	for _, k := range s {
		if string(k) == "." {
			currentDot += 1
		}
	}

	ans := currentDot

	currentSharp := 0
	for _, k := range s {
		if string(k) == "." {
			currentDot -= 1
		} else {
			currentSharp += 1
		}

		//fmt.Printf("dot: %d, sharp: %d\n", currentDot, currentSharp)

		ans = min(ans, currentDot+currentSharp)
	}

	return ans
}

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}
func oneStr() string {
	var a string
	fmt.Scan(&a)
	return a
}

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func scanNums() (nums []int) {
	s := nextLine()
	numStr := strings.Split(s, " ")

	for _, n := range numStr {
		i, _ := strconv.Atoi(n)
		nums = append(nums, i)
	}
	return nums
}

func scanStrings() (strs []string) {
	s := nextLine()
	list := strings.Split(s, " ")
	strs = append(strs, list...)
	return strs
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func sortAsc(a []int) []int {
	sort.Ints(a)
	return a
}

func sortDesc(a []int) []int {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	return a
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	if a == 0 && b == 0 {
		return 0
	}
	return a * b / gcd(a, b)
}

func cumSum(nums []int) []int {
	sums := []int{0}

	for i := 0; i < len(nums); i++ {
		sums = append(sums, sums[i]+nums[i])
	}
	return sums
}
//  [go]
package main

import (
  "fmt"
)

func min(a, b int) int {
  if a < b {
    return a
  }
  return b
}

func main() {
  var n int
  var s string
  fmt.Scan(&n, &s)

  b := make([]int, n + 1)
  w := make([]int, n + 1)
  for i := 0; i < n; i++ {
    w[i + 1] = w[i]
    b[i + 1] = b[i]
    if s[i] == '.' {
      w[i + 1]++
    } else {
      b[i + 1]++
    }
  }
  ans := n
  for i := 0; i <= n; i++ {
    ans = min(ans, b[i] + (w[n] - w[i]))
  }
  fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
	"io"
	"os"
)

func answer(reader io.Reader, writer io.Writer) {
	var n int
	var s string
	_, _ = fmt.Fscan(reader, &n)
	_, _ = fmt.Fscan(reader, &s)
	c1 := make([]int, n)
	c2 := make([]int, n)
	for i := 0; i < len(s); i++ {
		if string(s[i]) == "#" {
			if i == 0 {
				c1[0] = 1
			} else {
				c1[i] = c1[i-1] + 1
			}
		} else {
			if i == 0 {
				c1[0] = 0
			} else {
				c1[i] = c1[i-1]
			}
		}
		j := len(s) - i - 1
		if string(s[j]) == "." {
			if j == len(s)-1 {
				c2[j] = 1
			} else {
				c2[j] = c2[j+1] + 1
			}
		} else {
			if j == len(s)-1 {
				c2[j] = 0
			} else {
				c2[j] = c2[j+1]
			}
		}
	}
	v := c2[0]
	for i := 0; i < len(s)-1; i++ {
		r := c1[i] + c2[i+1]
		if r < v {
			v = r
		}
	}
	if c1[len(s)-1] < v {
		v = c1[len(s)-1]
	}
	_, _ = fmt.Fprintf(writer, "%d", v)
}

func main() {
	answer(os.Stdin, os.Stdout)
}
//  [ruby]
class SegTree
  attr_reader :size, :e, :f
  attr_accessor :seg

  def self.create(a=[],e,f)
    n = 1
    n *= 2 while n < a.size
    this = new(n,e,f)
    a.size.times do |i|
      this.seg[i+n] = a[i]
    end
    (n-1).downto(1) do |i|
      this.seg[i] = f[ this.seg[i*2],this.seg[i*2+1] ]
    end
    this
  end

  def initialize(n=2**32,e,f)
    @size = n
    @e = e
    @f = f
    @seg = Array.new(size*2, e)
  end

  def [](i)
    i += size
    seg[i]
  end

  def update(i,x)
    i += size
    seg[i] = x
    while i > 1
      i /= 2
      seg[i] = f[ seg[i*2], seg[i*2+1] ]
    end
  end

  def query(a,b)
    ans = e
    a += size; b += size
    while a < b
      (ans = f[ ans, seg[a] ]; a += 1) if a.odd?
      (b -= 1; ans = f[ ans, seg[b] ]) if b.odd?
      a /= 2; b /= 2
    end
    ans
  end

  def inspect
    { size: size, seg: seg }.to_s
  end
end

# SegTree.new(N,E,F) := 要素数N、単位元E、演算Fで初期化、ただしNは2の冪
# SegTree.create(A,E,F) := モノイドA、単位元E、演算Fで初期化で初期化
# update(i,x) := A[i]をxに更新
# query(a,b) := 半開区間[a,b)でのA[i]の演算結果
#
# 単位元を追加してモノイドにする例（gcd）
# E = -1
# F = -> x,y { x == E ? y : y == E ? x : x.gcd(y) }
# T = SegTree.create(a,E,F)

n = gets.to_i
Black = gets.chomp.chars.map{|c| c == "#" ? 1 : 0 }
White = Black.map{|i| 1 - i }

E = 0
F = -> x,y { x + y }
BlackTree = SegTree.create(Black,E,F)
WhiteTree = SegTree.create(White,E,F)

ans = 10**6
0.upto(n) do |i|
  num = BlackTree.query(0,i) + WhiteTree.query(i,n)
  ans = num if ans > num
end

puts ans
//  [ruby]
io = STDIN
n=io.gets.to_i
s=io.gets.chomp.split(//).chunk_while{|a,b|a==b}.to_a
size=s.size
def cnt_ar(ss,ch)
  ss.select{|ar|ar[0]==ch}.map{|ar|ar.size}
end
white=cnt_ar(s,".") #今の色の数
all_black_cnt=white.inject(0){|s,i|s+i}  #all blackにするために動かした数
ans=move=all_black_cnt
s.each do |ar|
  if ar[0]=="#"
    move+=ar.size
  else
    move-=ar.size
  end
  ans=[ans,move].min
end
puts ans
//  [ruby]
n = gets.to_i
s = gets.chomp

tmp1 = Hash.new(0)
tmp2 = Hash.new(0)

n.times do |i|
  if s[i] == "."
    tmp1[i] = 1
  else
    tmp2[i] = 1
  end
end

n.downto(0) do |i|
  tmp1[i] += tmp1[i + 1]
  tmp2[i] += tmp2[i + 1]
end

count = 0
min = Float::INFINITY

n.times do |i|
  next if s[i] == "."
  min = [min, count + tmp1[i]].min
  count += 1
end

puts [min, count].min
//  [rust]
use std::io::*;
use std::str::FromStr;

//https://qiita.com/tubo28/items/e6076e9040da57368845
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let s: Vec<char> = read::<String>().chars().collect();

    //累積和の準備
    let mut whsum = vec![0; n + 1];
    let mut blsum = vec![0; n + 1];
    for i in 0..n {
        match s[i] {
            '.' => {
                whsum[i + 1] = whsum[i] + 1;
                blsum[i + 1] = blsum[i];
            }
            '#' => {
                whsum[i + 1] = whsum[i];
                blsum[i + 1] = blsum[i] + 1;
            }
            _ => {}
        }
    }

    let mut ret: u64 = std::u64::MAX;
    for left in 0..=n {
        let mut tmp: u64 = 0;
        // left の黒を白に変える
        tmp += blsum[left] - blsum[0];
        // right の白を黒に変える
        tmp += whsum[n] - whsum[left];

        ret = std::cmp::min(tmp, ret);
    }
    println!("{}", ret);
}
//  [rust]
#![allow(non_snake_case)]
#![allow(unused_imports)]
use proconio::input;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::VecDeque;

fn main() {
    input! {
        N: usize,
        S: String,
    }

    // "#." はダメ
    // "##" ".#" ".." OK
    // 最終形は "#####" "......." "......######"
    // 一色にするのは簡単に計算できる。 "......#####"は?
    // どこを区切れ目にするかN通り * 個数カウント
    // 個数カウントをO(1)でやる → 累積和

    let whites: usize = S.chars().filter(|&c| c == '.').count();
    let blacks: usize = S.chars().filter(|&c| c == '#').count();
    let mut ans = min(whites, blacks);

    // 累積和を使う
    let mut white_acc: Vec<usize> = vec![0; N + 1];
    let mut black_acc: Vec<usize> = vec![0; N + 1];
    for i in 0..N {
        if &S[i..=i] == "#" {
            white_acc[i + 1] = white_acc[i];
            black_acc[i + 1] = black_acc[i] + 1;
        } else {
            white_acc[i + 1] = white_acc[i] + 1;
            black_acc[i + 1] = black_acc[i];
        }
    }

    // どこを黒の最初にするか?
    for i in 1..N {
        // [0 ~ i) までの黒石を白くする
        // [i ~ N) までの白石を黒くする
        let cand = black_acc[i] + (white_acc[N] - white_acc[i]);
        ans = min(ans, cand);
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{input, marker::Chars};

fn main() {
    input! {
        n: usize,
        s: Chars,
    }

    let mut count_white = vec![];
    let mut count_black = vec![];
    for &c in s.iter() {
        let a = if c == '#' { 1 } else { 0 };
        if let Some(&last) = count_black.last() {
            count_black.push(last + a);
        } else {
            count_black.push(a);
        }
    }
    for &c in s.iter() {
        let a = if c == '.' { 1 } else { 0 };
        if let Some(&last) = count_white.last() {
            count_white.push(last + a);
        } else {
            count_white.push(a);
        }
    }
    let num_white = *count_white.last().unwrap();
    for e in count_white.iter_mut() {
        *e = num_white - *e;
    }

    let mut ans = n;
    for i in 0..=n {
        let mut temp = 0;
        if i > 0 {
            temp += count_black[i - 1];
        }
        if i < n {
            temp += count_white[i];
        }

        ans = std::cmp::min(ans, temp);
    }

    println!("{}", ans);
}
//  [swift]
readLine()
let S=readLine()!.characters
var i=S.filter{$0>"#"}.count
print(S.reduce(i){min($0,$1>"#" ? --i:++i)})
//  [swift]
let N = Int(readLine()!)!
let S = readLine()!.characters
var cnt = S.reduce(0){$0+($1>"#" ?1:0)}
var ans = cnt
for c in S {
    let tmp = ans
    if c>"#" {
        cnt--
    } else {
        cnt++
    }
    ans = min(cnt, ans)
}
print(ans)
//  [swift]
readLine();var S=readLine()!.characters,i=S.filter{$0>"#"}.count;print(S.reduce(i){min($0,$1>"#" ? --i:++i)})
//  [python]
N = int(input())
a = list(map(int,input().rstrip().split(" ")))
K = sum(a)
now = 0
ans = 10 ** 15
for i in range(N -1):
    now += a[i]
    K -= a[i]
    ans = min(ans,abs(K - now))
print(ans)
//  [python]
import sys
input = sys.stdin.readline
def main():
    N = int(input())
    A = list(map(int, input().split()))
    X = [0]*(N+1)

    for i in range(1,N+1):
        X[i] += A[i-1] + X[i-1]
    ans  = float('INF') 
    for i in range(1,N):
        ans = min(ans,abs(X[N] - 2*X[i]))
    print(ans)

if __name__ == '__main__':
    main()
//  [python]
def main():
    N = int(input())
    A = tuple(map(int, input().split()))

    tot = sum(A)

    ans = (10 ** 9) * (2 * 10 ** 5) + 1
    s = 0
    for x in A[:-1]:
        s += x + x
        diff = abs(tot - s)
        if ans > diff:
            ans = diff

    print(ans)


if __name__ == '__main__':
    main()
//  [python]

from collections import defaultdict, Counter
import math
from bisect import bisect_left, bisect_right
import numpy as np

#### START
n = int(input())
a = list(map(int,input().split()))

ans = 10**100
res = np.cumsum(a)

print(min([abs(res[-1]-res[i]-res[i]) for i in range(len(res)-1)]))
//  [python]
import numpy as np

N = int(input())
A = list(map(int, input().split()))

A = np.array(A)
A_cumsum = np.cumsum(A)

solver = []
for i in range(N-1):
  snuke = A_cumsum[i]
  racoon = A_cumsum[-1] - A_cumsum[i]
  solver.append(np.abs(snuke - racoon))
  
print(min(solver))
//  [python]
import numpy as np
N=int(input())
X=[int(x) for x in input().split()]
Y=np.cumsum(X)
P=sum(X)
answer=float('inf')
for i in range(N-1):
  answer =min (answer,abs(P-2*Y[i]))
print(answer)
//  [java]
import java.io.IOException;
import java.util.NoSuchElementException;

import java.io.InputStream;

import java.io.PrintWriter;

@SuppressWarnings("unchecked")
public class Main {
    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);

        final int N = nextInt();

        int[] a = new int[N];

        long sum = 0L;

        for (int i = 0; i < N; i++) {
            a[i] = nextInt();
            sum += a[i];
        }

        long min = 200000000000001L;

        long tmp = 0L;

        // 必ず 1枚 は取る
        for (int i = 0; i < N - 1; i++) {
            tmp += a[i];
            // |x - y| = |x - (sum - x)|
            min = Math.min(min, Math.abs(2L * tmp - sum));
        }


        out.println(min);

        out.flush();
    }

    // FastScanner start
    static final InputStream in = System.in;
    static final byte[] buffer = new byte[1024];
    static int ptr = 0;
    static int buflen = 0;
    static boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    static int readByte() {
        if (hasNextByte()) return buffer[ptr++];
        else return -1;
    }
    static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }
    static boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
        return hasNextByte();
    }
    static String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    static long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if(b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    static int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }
    static double nextDouble() {
        return Double.parseDouble(next());
    }
    // FastScanner end
}
//  [java]
import java.util.*;
import java.text.DecimalFormat;
// warm-up
public class Main {

	static void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt(), no = N, i = 0;
		double min = Double.MAX_VALUE, s = 0, t = 0;
		double[] a = new double[N];
		while (N-->0) {
			double b = sc.nextDouble();
			a[i++] = b; s+=b;
		}
		N = no;
		for (i=N-1; i>0; i--) {
			t+=a[i];
			min = Math.min(Math.abs(s-(2*t)), min);
		}
		System.out.println(new DecimalFormat("#").format(min));
		sc.close();		
	}

	public static void main(String args[]) {
		solve();
	}

}
//  [java]
import java.util.*;
import java.text.DecimalFormat;
// warm-up
public class Main {

	static void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt(), no = N, i = 0;
		double min = Double.MAX_VALUE, s = 0, t = 0;
		double[] a = new double[N];
		while (N-->0) {
			double b = sc.nextDouble();
			a[i++] = b; s+=b;
		}
		N = no;
		for (i=N-1; i>0; i--) {
			t+=a[i];
			if (Math.abs(s-(2*t))<min) min = Math.abs(s-(2*t));
		}
		System.out.println(new DecimalFormat("#").format(min));
		sc.close();		
	}

	public static void main(String args[]) {
		solve();
	}

}
//  [java]
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created by DELL on 2017/7/15.
 */
public class Main {
    public static void main(String[] args) {

        Scanner in=new Scanner(System.in);
        long sum=0,j=0;
        List<Long> list=new ArrayList();
        BigInteger min;
        int N=in.nextInt();
        for (int i = 0; i < N; i++) {
            list.add(in.nextLong());
        }
        long summ=list.parallelStream().mapToLong(x->x).sum();
        sum+=list.get(0);
        if(N>2){
            min=BigInteger.valueOf(Math.abs(2*sum-summ));
        for (int i = 1 ; i <N-1 ; i++) {
            sum+=list.get(i);
            if(BigInteger.valueOf(Math.abs(2*sum-summ)).compareTo(min)==-1){
                min=BigInteger.valueOf(Math.abs(2*sum-summ));
            }
        }
            System.out.println(min);
        }
        else System.out.println(Math.abs(list.get(0)-list.get(1)));



    }

}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
inline void rd(int &x){
  int k, m=0;
  x=0;
  for(;;){
    k = getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
inline void wt_L(char a){
  putchar_unlocked(a);
}
inline void wt_L(long long x){
  char f[20];
  int m=0, s=0;
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    putchar_unlocked('-');
  }
  while(s--){
    putchar_unlocked(f[s]+'0');
  }
}
template<class S, class T> inline S chmin(S &a, T b){
  if(a>b){
    a=b;
  }
  return a;
}
int N;
int A[200000];
int main(){
  int i;
  long long d, res=4611686016279904256LL, sum=0;
  rd(N);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=0;Lj4PdHRW<N;Lj4PdHRW++){
      rd(A[Lj4PdHRW]);
    }
  }
  for(i=0;i<N;i++){
    sum += A[i];
  }
  d = 0;
  for(i=0;i<N-1;i++){
    d += A[i];
    chmin(res, abs(sum - 2*d));
  }
  wt_L(res);
  wt_L('\n');
  return 0;
}
// cLay varsion 20190721-1

// --- original code ---
// int N, A[2d5];
// {
//   int i;
//   ll d, sum = 0, res = ll_inf;
// 
//   rd(N,A(N));
//   
//   rep(i,N) sum += A[i];
// 
//   d = 0;
//   rep(i,N-1){
//     d += A[i];
//     res <?= abs(sum - 2d);
//   }
//   
//   wt(res);
// }
//  [cpp]
#define _CRT_SECURE_NO_WARNINGS
#define __STDC_FORMAT_MACROS
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <vector>

using namespace std;

template<class T> void gc(T &x)
{
    char c;
    int s = 0;
    x = 0;

    c = getchar_unlocked();

    if (c == '-') s = 1;
    else if ('0' <= c && c <= '9')  x = c - '0';

    while (true)
    {
        c = getchar_unlocked();

        if (c < '0' || c > '9') break;
        x = x * 10 + (c - '0');
    }

    if (s) x = -x;
}

int main()
{
    int N;

    gc(N);

    int tmp;
    int64_t ttl = 0;
    vector<int> a(N);
    for (int i = 0; i < N; i++)
    {
        gc(tmp);
        a[i] = tmp;
        ttl += tmp;
    }

    int64_t now = 0;
    int64_t mn = INT64_MAX;
    for (int i = 0; i < N - 1; i++)
    {
        now += a[i];
        mn = min(mn, abs(ttl - 2 * now));
    }

    printf("%" PRId64 "\n", mn);
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = s; i < (int)(n); i++)
#define rep3(i, s, n) for (int i = s; i > (int)(n); i--)
#define all(obj) obj.begin(), obj.end()
#define db(x) cerr << #x << ":" << x << " "
#define dbl(x) cerr << #x << ":" << x << "\n"
#define dbv(vec) cerr << #vec << ":"; for (auto e : vec) cerr << e << " "; cout << "\n"
#define dbvv(vv) cerr << #vv << ":\n"; for (auto vec : vv) { for (auto e : vec) cerr << e << " "; cerr << endl; }
#define YN(f) cout << (f ? "YES" : "NO") << endl
#define Yn(f) cout << (f ? "Yes" : "No") << endl
#define yn(f) cout << (f ? "yes" : "no") << endl
/*
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using pii = pair<int, int>;
*/

int main() {
	int N; cin >> N;
	vector<long long> a(N); rep(i, N) cin >> a.at(i);
	// long long x = a[0], y = a[N - 1];
	vector<long long> b(N - 1); rep2(i, 1, N - 1) b[i] = b[i - 1] + a[i];
	dbv(b);
	long long ans = 0; for(long long ai : a) ans += abs(ai); dbl(ans);
	rep(i, N - 1) {
		long long x = a[0] + b[i], y = (b[N - 2] - b[i]) + a[N - 1];
		db(x); db(y); dbl(x - y);
		ans = min(ans, abs(x - y));
	}
	cout << ans << endl;
}
//  [cpp]
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0;i < (n);i++)
using ll = long long;
const ll MOD=1000000007;



int main() 
{
  ll N; cin>>N;
  ll sum=0;
  vector<ll> A(N);
  rep(i,N)
  {
    cin>>A.at(i);
    sum+=A.at(i);
  }
  vector<ll> sa(N-1);
  ll sum2=0;
  rep(i,N-1)
  {
    sum2+=A.at(i);
    sa.at(i)=abs(sum-2*sum2);
  }
  sort(sa.begin(),sa.end());
  cout<<sa.at(0)<<endl;
  return 0;
}
//  [cpp]
#include <iostream>
#include <iomanip>
#include <vector>
#include <utility>
#include <map>
#include <algorithm>
#include <queue>
#include <cmath>
#include <numeric>
#include <set>

using namespace std;
struct aaa{aaa(){cin.tie(nullptr); ios::sync_with_stdio(false); cout<<fixed<<setprecision(20);};}aaa;
template <class T>ostream &operator<<(ostream &o,const vector<T>&v){o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
#define debug(v) {cerr<<"\033[1;36m[debug]\033[m "<<#v<<" : "<<v<<endl;}

using int64 = long long;

int main() {
    int64 n;
    cin >> n;
    vector<int64> a(n);
    for (int64 i=0; i<n; i++) cin >> a[i];

    vector<int64> right(n+1,0);
    vector<int64> left(n+1,0);
    for (int i=0; i<n; i++) {
        left[i+1] = left[i] + a[i];
        right[n-i-1] = right[n-i] + a[n-i-1];
    }

    int64 ans = LONG_MAX;
    for (int i=1; i<n; i++) ans = min(ans, abs(right[i] - left[i]));
    cout << ans << endl;
    debug(left);
    debug(right);
}
//  [c]
long S,s,m=(long)1<<60;a[2<<17];i;main(j){for(;~scanf("%d",a+i);++i)i?S+=a[i]:0;for(;j<i-1;m=fmin(m,labs(S-2*s)))s+=a[j++];printf("%ld",m);}
//  [c]
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 内部定数
#define D_ARRAY_MAX		200000									// 最大配列数

// 内部変数
static int si1Array[D_ARRAY_MAX];								// 配列
static int siACnt;												// 配列数

// 内部変数 - テスト用
#ifdef D_TEST
	static int siRes;
	static FILE *szpFpT, *szpFpA;
#endif

// 実行メイン
int
fMain(
	int piTNo					// <I> テスト番号 1～
)
{
	int i;
	char lc1Buf[1024], lc1Out[1024];

	// テストファイルオープン
#ifdef D_TEST
	sprintf(lc1Buf, ".\\Test\\T%d.txt", piTNo);
	szpFpT = fopen(lc1Buf, "r");
	sprintf(lc1Buf, ".\\Test\\A%d.txt", piTNo);
	szpFpA = fopen(lc1Buf, "r");
	siRes = 0;
#endif

	// 配列数取得
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpT);
#else
	fgets(lc1Buf, sizeof(lc1Buf), stdin);
#endif
	sscanf(lc1Buf, "%d", &siACnt);

	// 配列取得・合計取得
	long long llSum1 = 0;
	for (i = 0; i < siACnt; i++) {
#ifdef D_TEST
		fscanf(szpFpT, "%d", &si1Array[i]);
#else
		fscanf(stdin, "%d", &si1Array[i]);
#endif
		llSum1 += (long long)si1Array[i];
	}
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpT);
#else
	fgets(lc1Buf, sizeof(lc1Buf), stdin);
#endif

	// 初期値
	llSum1 -= (long long)si1Array[siACnt - 1];
	long long llSum2 = si1Array[siACnt - 1];
	long long llMin = llabs(llSum1 - llSum2);

	// 全パターンチェック
	for (i = siACnt - 2; i > 0; i--) {
		llSum1 -= (long long)si1Array[i];
		llSum2 += (long long)si1Array[i];
		long long llVal = llabs(llSum1 - llSum2);
		if (llMin > llVal) {
			llMin = llVal;
		}
	}

	// 結果セット
	sprintf(lc1Out, "%lld\n", llMin);

	// 結果表示
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, lc1Out)) {
		siRes = -1;
	}
#else
	printf("%s", lc1Out);
#endif

	// テストファイルクローズ
#ifdef D_TEST
	fclose(szpFpT);
	fclose(szpFpA);
#endif

	// テスト結果
#ifdef D_TEST
	if (siRes == 0) {
		printf("OK %d\n", piTNo);
	}
	else {
		printf("NG %d\n", piTNo);
	}
#endif

	return 0;
}

int
main()
{

#ifdef D_TEST
	int i;
	for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
		fMain(i);
	}
#else
	fMain(0);
#endif

	return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int main() {
	int n, a[200000];
	long long sum = 0, Spt = 0, min = 1e18;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
		sum += a[i];
	}
	for (int i = 0; i < n - 1; i++) {
		Spt += a[i];
		if (min > llabs(Spt - (sum - Spt))) {
			min = llabs(Spt - (sum - Spt));
		}
	}
	printf("%lld\n", min);
	return 0;
}
//  [c]
#include<stdio.h>
int main()
{
    long long int i,j,k,sum1=0,sum2=0,min,n,t;
    scanf("%lld",&n);
    long long int array[n];
    for(i=0;i<n;i++){
        scanf("%lld",&array[i]);
        if(i!=0){
            sum2=sum2+array[i];
        }
        else
            sum1=sum1+array[i];
    }
    if(sum1<sum2)
        min=sum2-sum1;
    else
        min=sum1-sum2;
    for(i=1;i<n-1;i++){
        sum1=sum1+array[i];
        sum2=sum2-array[i];
        if(sum2>sum1){
            if((sum2-sum1)<min)
                min=sum2-sum1;
        }
        else{
            if((sum1-sum2)<min)
                min=sum1-sum2;
        }
    }
    printf("%lld\n",min);
    return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,sw;
  sw=0;
  scanf("%d",&n);
long long int a[n],sum[n],ans,temp;
  scanf("%lld",&a[0]);
  sum[0]=a[0];
  for(i=1;i<n;++i)
  {
  scanf("%lld",&a[i]);
  sum[i]=sum[i-1]+a[i];
  }
  int cc=0;
  
  ans=llabs(sum[n-1]-sum[0]*2);
    for(i=1;i<n-1;++i)
    {
    temp=llabs(sum[n-1]-sum[i]*2);
    if(temp<ans) ans=temp;
    }
  printf("%lld",ans);
return 0;}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

int main(void){

    int N;

    scanf("%d", &N);

    long long a[N];

    long long sum = 0;

    for(int i = 0; i < N; i++){
        scanf("%lld", &a[i]);
        sum += a[i];
    }

    long long x = 0, y;
    long long min = 100000000000000000;

    for(int i = 0; i < N-1; i++){
        x += a[i];
        y = sum - x;
        if(llabs(x-y) < min){
            min = llabs(x-y);
        }
    }

    printf("%lld\n", min);

    return 0;
}
//  [javascript]
    // inputに入力データ全体が入る
function Main(input) {
	input = input.split("\n");
 
	var line1 = input[0].split(" ");
	var num = Number(line1[0])
	var data = input[1].split(" ");
	for(var i = 0; i<num; i++){
	    data[i] = Number(data[i]);
	}
	
	var sum = 0;

	for(var i = 0; i<num; i++){
	    sum += data[i];
    }

    var leftSum = 0
    var diff = 1e30;
    var ans = 1e30;

	for(var ite=0; ite<num-1;ite++){
	    leftSum += data[ite];
	    diff = Math.abs((sum-leftSum) - leftSum);
//	    console.log("i:"+ite+" ls:"+leftSum+" sum:"+sum+" diff:"+diff);
	    if(diff<ans){
	        ans = diff;
	    }
	}	
    
    console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
inp = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n')
N = inp.shift() * 1
l = inp.shift().split(' ')
sum = 0
a = []
for (i=0; i<N; i++) {
    sum += l[i] * 1
    a[i] = sum
}
min = Infinity
for (i=0; i<N-1; i++) {
    d = Math.abs(a[i] - (sum - a[i]))
    if (min > d) {
        min = d
    } 
}
console.log(min)
//  [javascript]
var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input,
  "index" : 0,
  "max" : input.length,
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  },
  "hasNext" : function(){return (this.index < this.max);}
}
Main();
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//1:数値へ変換 2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字に分割 7:1文字に分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
  var N = myconv(next(),1);
  var list = myconv(next(),4);
  var max = 0;
  for(var i = 0; i < N; i++){
    max += list[i];
  }
  var mae = 0;
  var output = Math.pow(10,15);
  for(var i = 0; i < N - 1; i++){
    mae += list[i];
    var ato = max - mae;
    output = Math.min(output,Math.abs(mae - ato));
  }
  myout(output);
}
//  [javascript]
function main( input ){

  var as = input.split( /\n/ )[1]
                .split( /\s/ )
                .map( function( n ){
                  return parseInt( n )
                } )

  var r = 0
  for( var i=1; i<as.length; i++ )
    r += as[i]

  var position = 1
  var l = as[0]
  var m = Math.abs( r - as[0] )

  for( ; as.length-1>position; position++ ){
    l += as[position]
    r -= as[position]

    if( m > Math.abs( l - r ) )
      m = Math.abs( l - r )
  }

  console.log( m )

}

main(
  require( 'fs' )
    .readFileSync( '/dev/stdin', 'utf8' )
)
//  [javascript]
'use strict'

function main(input) {
  input = input
    .trim()
    .split('\n')
    .map(v => v.split(' ').map(Number))

  const n = input[0]
  const cards = input[1]
  const sums = [0]
  // 累積和
  for (let i = 0; i < n; i++) {
    sums.push(sums[i] + cards[i])
  }

  let min = Number.MAX_SAFE_INTEGER
  const total = sums[n]
  for (let i = 1; i < n; i++) {
    let tmp = Math.abs(total - sums[i] - sums[i])
    min = Math.min(min, tmp)
  }

  console.log(min)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    const n = nextInt()
    const a = nextIntArray()
    let y = 0
    for(let i = 0; i<a.length; i++){
        y += a[i]
    }
    let x = 0
    let min = Number.POSITIVE_INFINITY
    for(let i = 0;i<a.length-1; i++){
        x += a[i]
        y -= a[i]
        min = Math.min(min, Math.abs(x-y))
    }
    console.log(min)
}
Main()
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

func b2i(a []byte) (n int) {
	for _, v := range a {
		n = n*10 + int(v-48)
	}
	return
}

func ri() (n int) {
	sc.Scan()
	b := sc.Bytes()
	if b[0] == 45 {
		return -b2i(b[1:])
	} else {
		return b2i(b)
	}
}

func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func main() {
	sc.Split(bufio.ScanWords)
	n := ri()

	cumSum := make([]int, n)
	sum := 0
	for i := 0; i < n; i++ {
		sum += ri()
		cumSum[i] = sum
	}

	minDiff := 2100000000
	for i := 0; i <= n-2; i++ {
		d := diff(cumSum[i], sum-cumSum[i])
		if d < minDiff {
			minDiff = d
		}
	}
	fmt.Println(minDiff)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for C - Splitting Pile
	var N int
	fmt.Scanf("%d", &N)

	sc.Split(bufio.ScanWords)
	a := make([]int, N)
	sum := make([]int, N)
	var temp int
	for i := 0; i < N; i++ {
		a[i] = nextInt()
		temp += a[i]
		sum[i] = temp
	}

	var x, abs int
	var ans int = 100000000000
	for i := 0; i < N-1; i++ {
		x = sum[i]
		abs = int(math.Abs(float64(sum[N-1] - 2*x)))
		if ans > abs {
			ans = abs
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string   { sc.Scan(); return sc.Text() }
func scanRunes() []rune    { return []rune(scanString()) }
func scanInt() int         { a, _ := strconv.Atoi(scanString()); return a }
func scanInt64() int64     { a, _ := strconv.ParseInt(scanString(), 10, 64); return a }
func scanFloat64() float64 { a, _ := strconv.ParseFloat(scanString(), 64); return a }

func scanInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = scanInt()
	}
	return res
}

func debug(a ...interface{}) { fmt.Fprintln(os.Stderr, a...) }

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

//•*¨*•.¸¸♪main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)
func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1001001)

	n := scanInt()
	a := scanInts(n)

	sum := 0
	for i := 0; i < n; i++ {
		sum += a[i]
	}

	ans := 1 << 60
	x := 0
	for i := 0; i < n-1; i++ {
		x += a[i]
		sum -= a[i]
		ans = min(ans, abs(sum-x))
	}
	fmt.Fprintln(wr, ans)
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var n, a, sum int
	fmt.Scan(&n)
	s := make([]int, n)
	for i := range s {
		fmt.Scan(&a)
		sum += a
		s[i] = sum
	}

	ans := math.MaxInt32
	for i := 0; i < n-1; i++ {
		ans = min(ans, abs(2*s[i]-s[n-1]))
	}

	fmt.Println(ans)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var n int
	fmt.Scan(&n)
	arr := make([]int, n)
	sum1 := 0
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Scan(&tmp)
		arr[i] = tmp
		sum1 += tmp
	}
	mn := math.MaxInt32
	sum2 := 0
	for i := 0; i < n - 1; i++ {
		sum2 += arr[i]
		sum1 -= arr[i]
		tmp := abs(sum1 - sum2)
		if mn > tmp {
			mn = tmp
		}
	}
	fmt.Println(mn)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}
//  [go]
package main

import (
	"fmt"
	"math"
)

const inf = 10000000000.0

func main() {
	var n int
	fmt.Scan(&n)

	arrA := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arrA[i])
	}

	cumSumA := make([]int, n+1)
	cumSumA[0] = 0
	for i, a := range arrA {
		cumSumA[i+1] = cumSumA[i] + a
	}

	ans := inf
	for i := 1; i < n; i++ {
		if math.Abs(float64(cumSumA[n]-(cumSumA[i]*2))) < ans {
			ans = math.Abs(float64(cumSumA[n] - cumSumA[i]*2))
		}
	}

	fmt.Println(int(ans))
}
//  [ruby]
_ = gets.to_i
a = gets.split.map(&:to_i)

su = a.inject(:+)
ar = 0
ans = 10 ** 12
a.pop
a.each do |e|
    su -= e
    ar += e
    x = (su-ar).abs
    ans = x if ans > x
end

puts ans
//  [ruby]
n = gets.to_i
a = gets.split.map &:to_i;
total = a.inject(:+)
x = 0;  y = total;  res = 10**9 * 2
0.upto(n-2) {|i|
  x += a[i];  y = total - x
  res = ((x-y).abs < res ? (x-y).abs : res)
}
puts res
//  [ruby]
n=gets.chomp.to_i
A=gets.chomp.split.map(&:to_i)
y=A.inject(:+)
x=0
ans=10**12
A.pop
A.each do |e|
   x+=e
   y-=e
   z=(y-x).abs
   ans=z if ans > z
end
puts ans.abs
//  [ruby]
N = gets.to_i
a = gets.split(' ').map(&:to_i)

def sum(arr)
  arr.inject(&:+)
end

ans = 10**10
su = 0
ara = a.inject(&:+)
N.times do |i|
  break if i == N-1
  su += a[i]
  ara -= a[i]

  cal = [su, ara].max - [su, ara].min
  ans = [ans, cal].min

  break if ans == 0
end

p ans
//  [ruby]
n,*a=`dd`.split.map &:to_i
(1...n).each{|i|a[i]+=a[i-1]}
p (0..n-2).map{|i|(a[i]-(a[n-1]-a[i])).abs}.min
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end


n = gif

a = gi
s1 = a.shift
s2 = a.inject(:+)
ans = (s1-s2).abs
rep (a.size-1) do |i|
s1 += a[i]
s2 -= a[i]
tmp = (s1-s2).abs
ans = tmp if ans > tmp
end

puts ans
//  [rust]
use std::io;

#[allow(unused_macros)]
macro_rules! input {
    ( $($x:expr ),*) => {
        {
            let temp_str = input_line_str();
            let mut split_result_iter = temp_str.split_whitespace();
                $(
                let buf_split_result = split_result_iter.next();
                let buf_split_result = buf_split_result.unwrap();
                    ($x) = buf_split_result.parse().unwrap();
                )*
        }
    };
}

#[allow(dead_code)]
fn input_line_str() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(dead_code)]
fn p<T>(t: T)
where
    T: std::fmt::Display,
{
    println!("{}", t);
}

const SPLIT_DELIMITER: char = ' ';

#[allow(dead_code)]
fn input_vector<T>() -> Vec<T>
where
    T: std::str::FromStr,
{
    let mut v: Vec<T> = Vec::new();

    let s = input_line_str();
    let split_result = s.split(SPLIT_DELIMITER);
    for z in split_result {
        let buf = match z.parse() {
            Ok(r) => r,
            Err(_) => panic!("Parse Error"),
        };
        v.push(buf);
    }
    v
}

fn main() {
    let n: usize;
    input!(n);
    let v = input_vector::<isize>();
    let mut take_a = v[0];
    let mut take_b = 0;
    for z in &v {
        take_b += *z;
    }
    take_b -= *v.first().unwrap();
    let mut ans: isize = (take_a - take_b).abs();
    for z in &v[1..v.len() - 1] {
        let ansbuf = (take_a - take_b).abs();
        ans = std::cmp::min(ansbuf, ans);
        take_a += *z;
        take_b -= *z;
    }
    p(ans);
}
//  [rust]
use std::io;

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn main() {
    let hoge = get_line();
    let fuga = get_line();
    let n: usize = hoge.trim().parse().unwrap();
    let a: Vec<i64> = fuga.trim().split(" ").map(|x| x.parse().unwrap()).collect();
    let X: i64 = a.iter().sum();
    let mut x = 0;
    let mut result = std::i64::MAX;
    for i in 0..n-1 {
        x += a[i];
        result = if (result > (X - 2 * x).abs()) {
            (X - 2 * x).abs()
        } else {
            result
        };
    }
    println!("{}", result);
}
//  [rust]
use std::io::prelude::*;

fn input<T>() -> T
where
    T: std::str::FromStr,
{
    let stdin = std::io::stdin();
    let token: String = stdin
        .lock()
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().unwrap()
}

fn main() {
    let n: usize = input();
    let a: Vec<i64> = (0..n).map(|_| input()).collect();

    let mut sum = vec![0; n + 1];
    for i in 0..n {
        sum[i + 1] = sum[i] + a[i];
    }

    let mut ans = i64::max_value();
    for i in 1..n {
        ans = std::cmp::min(ans, (sum[i] - (sum[n] - sum[i])).abs());
    }

    println!("{}", ans);
}
//  [rust]

use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
  let stdin = stdin();
  let stdin = stdin.lock();
  let token: String = stdin
    .bytes()
    .map(|c| c.expect("failed to read char") as char)
    .skip_while(|c| c.is_whitespace())
    .take_while(|c| !c.is_whitespace())
    .collect();
  token.parse().ok().expect("failed to parse token")
}

use std::cmp::{max, min};
// use std::collections::BinaryHeap;

fn main() {
  let n = read::<i64>();
  let mut a_vec = vec![];
  let mut total = 0;
  let mut subsc = 0;
  let mut ans = 100000000000;

  for _ in 0..n {
    let a = read::<i64>();
    a_vec.push(a);
    total += a;
  }

  for i in 0..n - 1 {
    subsc += a_vec[i as usize];
    total -= a_vec[i as usize];
    ans = min(ans, (total - subsc).abs());
  }

  println!("{}", ans);
}
//  [swift]
let N = Int(readLine()!)!
let a = readLine()!.characters.split(" ").map{Int(String($0))!}
var x = a[0]
var y = a.reduce(0){$0+$1} - a[0]
var ans = abs(x-y)
for i in 1..<N-1 {
    x += a[i]
    y -= a[i]
    ans = min(abs(x-y), ans)
}
print(ans)
//  [typescript]
"use strict";

main(require("fs").readFileSync("/dev/stdin", "utf8"));

function main(input) {
  const [[n], cards] = input.split("\n").map(s => s.split(" ").map(Number));

  const targetValue = cards.reduce((p, c) => p + c) / 2;

  let currSum = 0;
  let diff = Infinity;
  for(let i = 0; i < n - 1; i++) {
    currSum += cards[i];
    diff = Math.min(diff, Math.abs(targetValue - currSum));
  }

  const ans = diff * 2;
  console.log(ans);
}
//  [python]
#A問題
h,a=map(int,input().split())
import math
print(math.ceil(h/a))
import time
time.sleep(1.98)