jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
#n,k=200000,200000
#a=[0]*200000
while k>0&&a!=[n]*n
  b=[]
  l=[0]*n
  c=0
  0.upto(n-1) do |i|
    c+=1
    if i+a[i]<n-1
      l[i+a[i]]+=1
    else
      l[n-1]+=1
    end
    b[i]=c
    c-=l[i]
  end
  l=[0]*n
  c=0
  (n-1).downto(0) do |i|
    if i-a[i]>0
      l[i-a[i]]+=1
    else
      l[0]+=1
    end
    b[i]+=c
    c-=l[i]
    c+=1
  end
  a=b.dup
  k-=1
end
puts a.join(" ")
//  [rust]
use itertools::Itertools as _;
use itertools_num::ItertoolsNum as _;
use proconio::input;
use std::cmp;

fn main() {
    input! {
        n: usize,
        k: usize,
        mut r#as: [usize; n],
    }

    for _ in 0..k {
        let mut imos = vec![0; n + 1];

        for (i, &a) in r#as.iter().enumerate() {
            let l = i.saturating_sub(a);
            let r = cmp::min(i + a + 1, n);
            imos[l] += 1;
            imos[r] -= 1;
        }

        r#as = imos[..n].iter().map(|&c| c as usize).cumsum().collect();

        if r#as.iter().all(|&a| a == n) {
            break;
        }
    }

    println!("{}", r#as.into_iter().format(" "));
}
//  [rust]
#![allow(unused_imports)]
use std::cmp::*;
use std::collections::*;
use itertools::Itertools;
use proconio::{input, marker::*, fastout};
use superslice::*;

#[fastout()]
fn main() {
    input! {
        n: i64, k: i64,
        mut aa: [i64; n as usize]
    }
    
    for _ in 0..k {
        let mut memo = vec![0i64; n as usize + 1];
        for i in 0..n {
            let left = max(0, i - aa[i as usize]) as usize;
            let right = min(n, i + aa[i as usize] + 1) as usize;
            memo[left] += 1;
            memo[right] -= 1;
        }
        let mut aa2 = vec![0; n as usize];
        let mut prev = 0;
        for i in 0..n as usize {
            aa2[i] = prev + memo[i];
            prev = aa2[i];
        }
        aa = aa2;
        if aa.iter().all(|v| *v == n) {
            break;
        }
    }
    for v in aa {
        print!("{} ", v);
    }

}
//  [rust]
use std::cmp;
use std::fmt::Debug;
use std::str::FromStr;

#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim()
        .split_whitespace()
        .map(|c| T::from_str(c).unwrap())
        .collect()
}

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

fn main() {
    let line = read_as_vec::<usize>();
    let (n, k) = (line[0], line[1]);
    let mut cur_lamps = read_as_vec::<i64>();

    for _ in 0..k {
        let mut v: Vec<i64> = vec![0; n];

        for i in 0..n {
            let left = cmp::max(0, i as i64 - cur_lamps[i]) as usize;
            let right = cmp::min(n, i + cur_lamps[i] as usize) + 1;
            v[left] += 1;
            if right < n {
                v[right] -= 1;
            }
        }

        let mut cur = 0;
        for i in 0..n {
            cur += v[i];
            v[i] = cur;
        }
        dbg!(&v);
        cur_lamps = v;
        if cur_lamps.iter().all(|x| *x == n as i64) {
            break;
        }
    }

    for i in 0..n {
        print!("{} ", cur_lamps[i]);
    }
}
//  [swift]
let NK: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
let N: Int = NK[0]
let K: Int = NK[1]
var seqNow: [Int] = readLine()!.split(separator: " ").map { Int($0)! }

for _ in 0..<K {
    var seqNext = Array(repeating: 0, count: N+1)

    for (i, a) in seqNow.enumerated() {
        let left: Int = max(0, i-a)
        let right: Int = min(N, i+1+a)
        
        seqNext[left] += 1
        seqNext[right] += -1
    }
    for i in 1..<N {
        seqNext[i] = seqNext[i] + seqNext[i-1]
    }
    if seqNow[0..<N] == seqNext[0..<N] { break }
    seqNow[0..<N] = seqNext[0..<N]
}
var res: String = ""
for s in seqNow[0..<N-1]{
    res += "\(s) "
}
print(res + String(seqNow[N-1]))
//  [swift]
import Foundation

private func readWords<T>(_ f: (Substring) -> T) -> [T] {
    return readLine()!.split(separator: " ").map(f)
}

prefix operator *
prefix func *<T>(a: inout IndexingIterator<[T]>) -> T {
    return a.next()!
}

func mainC() {
    var nk = readWords { Int($0)! }.makeIterator()
    let n = *nk
    let k = min(50, *nk)
    
    var A = readWords { Int($0)! }
    
    for _ in 1...k {
        var B = [Int](repeating: 0, count: n+1)
        for (i, a) in A.enumerated() {
            let l = max(0, i - a)
            let r = min(n, a + i + 1)
            B[l] += 1
            B[r] -= 1
        }
        
        var total = 0
        for i in 0..<n {
            A[i] = total + B[i]
            total = A[i]
        }
    }
    
    print(A.map{ $0.description }.joined(separator: " "))
    
}

mainC()
//  [swift]
import Foundation

private func readWords<T>(_ f: (Substring) -> T) -> [T] {
    return readLine()!.split(separator: " ").lazy.map(f)
}

prefix operator *
prefix func *<T>(a: inout IndexingIterator<[T]>) -> T {
    return a.next()!
}

func mainC() {
    var nk = readWords { Int($0)! }.makeIterator()
    let n = *nk
    let k = min(50, *nk)
    
    var A = readWords { Int($0)! }
    
    for _ in 1...k {
        var B = [Int](repeating: 0, count: n+1)
        for (i, a) in A.enumerated() {
            let l = max(0, i - a)
            let r = min(n, a + i + 1)
            B[l] += 1
            B[r] -= 1
        }
        
        var total = 0
        for i in 0..<n {
            A[i] = total + B[i]
            total = A[i]
        }
    }
    
    print(A.lazy.map{ $0.description }.joined(separator: " "))
    
}

mainC()
//  [swift]
let NK: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
let As: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
var seqNow: [Int] = Array(repeating: 0, count: NK[0]+1)
seqNow[0..<NK[0]] = As[0..<NK[0]]

for _ in 0..<NK[1] {
    var seqNext = Array(repeating: 0, count: NK[0]+1)
    var NCount = 0
    for (i, a) in seqNow.enumerated() {
        seqNext[max(0, i-a)] += 1
        seqNext[min(NK[0], i+1+a)] += -1
    }
    seqNow[0] = seqNext[0]
    for i in 1..<NK[0] {
        seqNow[i] = seqNow[i-1] + seqNext[i]
        if seqNow[i] == NK[0] { NCount += 1 }
    }
    if NCount == NK[0] { break }
}
var res: String = ""
for s in seqNow[0..<NK[0]-1]{
    res += "\(s) "
}
print(res + String(seqNow[NK[0]-1]))
//  [swift]
let NK: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
let As: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
var seqNow: [Int] = Array(repeating: 0, count: NK[0]+1)
//var seqNext: [Int] = Array(repeating: 0, count: NK[0]+1)
seqNow[0..<NK[0]] = As[0..<NK[0]]

for _ in 1...NK[1] {
    var seqNext = Array(repeating: 0, count: NK[0]+1)
    for (i, a) in seqNow.enumerated() {
        seqNext[max(0, i-a)] += 1
        seqNext[min(NK[0], i+1+a)] += -1
    }
    seqNow[0] = seqNext[0]
    for i in 1..<NK[0] {
        seqNow[i] = seqNow[i-1] + seqNext[i]
    }
}
var res: String = ""
for s in seqNow[0..<NK[0]-1]{
    res += "\(s) "
}
print(res + String(seqNow[NK[0]-1]))
//  [swift]
import Foundation

let line = readLine()!.components(separatedBy: " ").map { Int($0)! }
let N = line[0]
let K = line[1]
var A = readLine()!.components(separatedBy: " ").map { Int($0)! }

var zero = Array.init(repeating: 0, count: N)
var B = zero

for _ in 0..<K {
    for i in 0..<N {
        if A[i] == 0 {
            B[i] += 1
        } else {
            let s = 0 < i - A[i] ? i - A[i] : 0
            let e = i + A[i] < N ? i + A[i] : N - 1
            for t in s...e {
                B[t] += 1
            }
        }
    }
    A = B
    B = zero
}

let ans = A.map { String($0) }.joined(separator: " ")
print(ans)
//  [typescript]
import * as fs from "fs";

let [line1, line2] = fs.readFileSync("/dev/stdin", "utf8").trim().split('\n');

let [N, K] = line1.split(" ").map(Number);
let A = line2.split(" ").map(Number);

function makeOneStep(A: number[]): [boolean, number[]] {
    let B: number[] = new Array(N).fill(0);
    for(let i=0; i<N; i++) {
        let left = Math.max(0, i-A[i]), right = i+A[i];
        B[Math.max(0, left)] += 1;
        if (right+1 < N)
            B[right+1] -= 1;
    }
    let converged = true;
    for(let i=1; i<N; i++) {
        B[i] += B[i-1]
        converged = converged && B[i] == N;
    }
    return [converged, B];
}

let converged: boolean;

for(let i=0; i<K; i++) {
    [converged, A] = makeOneStep(A);
    if (converged)
        break;
}

console.log(A.map((a) => {return a.toString();}).join(" "));
//  [typescript]
// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N, K] = r.nn()
    let A = r.nn()

    for (let i = 0; i < K; i++) {
      let lightTable = {}
      const next: number[] = []
      let l = 0

      for (let j = 0; j < N; j++) {
        next[j] = l + 1
        if (!lightTable[j + A[j]]) lightTable[j + A[j]] = 0
        lightTable[j + A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      l = 0
      lightTable = {}
      for (let j = N - 1; j >= 0; j--) {
        next[j] += l
        if (!lightTable[j - A[j]]) lightTable[j - A[j]] = 0
        lightTable[j - A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      // console.log(next.join(' '))
      A = next
      if (A.every((v) => v === N)) {
        break
      }
    }

    return A
  }

  const _io = (i = 0) => {
    const str = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}
//  [typescript]
// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N, K] = r.nn()
    let A = r.nn()

    for (let i = 0; i < K; i++) {
      let lightTable = {}
      const next: number[] = []
      let l = 0

      for (let j = 0; j < N; j++) {
        next[j] = l + 1
        if (!lightTable[j + A[j]]) lightTable[j + A[j]] = 0
        lightTable[j + A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      l = 0
      lightTable = {}
      for (let j = N - 1; j >= 0; j--) {
        next[j] += l
        if (!lightTable[j - A[j]]) lightTable[j - A[j]] = 0
        lightTable[j - A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      // console.log(next.join(' '))
      A = next
      if (A.every((v) => v === K)) {
        break
      }
    }

    return A
  }

  const _io = (i = 0) => {
    const str = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}
//  [typescript]
// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N, K] = r.nn()
    let A = r.nn()

    const l = Math.min(K, 10 ** 5 / N)

    for (let i = 0; i < l; i++) {
      let lightTable = {}
      const next: number[] = []
      let l = 0

      for (let j = 0; j < N; j++) {
        next[j] = l + 1
        if (!lightTable[j + A[j]]) lightTable[j + A[j]] = 0
        lightTable[j + A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      l = 0
      lightTable = {}
      for (let j = N - 1; j >= 0; j--) {
        next[j] += l
        if (!lightTable[j - A[j]]) lightTable[j - A[j]] = 0
        lightTable[j - A[j]]--

        l += 1
        l += lightTable[j] || 0
      }

      // console.log(next.join(' '))
      A = next
    }

    return A
  }

  const _io = (i = 0) => {
    const str = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}
//  [python]
a,b,x=map(int,input().split());print(b//x-~-a//x)
//  [python]
a, b, x = map(int, input().split())
if a == 0:
    print(b // x + 1)
else:
    a -= 1
    print(b // x - a // x)
//  [python]
import sys

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    a, b, x = map(int, input().split())
    ans = b//x - (a-1)//x
    print(ans)


if __name__ == '__main__':
    solve()
//  [python]
a = input().split(" ")
b = int(a[1])
x = int(a[2])
a = int(a[0])
print(int((b - a + 1) // x))
//  [python]
a,b,x = map(int,input().split())

p = (b-a+1)//x
N = a+p*x

while N <= b:
  if N%x == 0:
    p += 1
    break
  else:
    N += 1

print(p)
//  [python]
def input_int():
    return(int(input()))

def input_int_list():
    return(list(map(int,input().split())))

def input_int_map():
    return(map(int,input().split()))


def run():
    a, b, x = input_int_map()
    result = count_num(b, x) - count_num(a - 1, x)
    print(result)

def count_num(num, x):

    if num < 0:
        return 0

    return num // x

run()

# 2 4 3

# 3 4 3

# 2 6 3
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    long a, b, x;

    public static void main(String args[]) {
        new Main().run();
    }

    void run() {
        FastReader sc = new FastReader();
        a = sc.nextLong();
        b = sc.nextLong();
        x = sc.nextLong();
        solve();
    }

    void solve() {
        long removedNum = (a % x == 0) ? a / x - 1 : a / x;
        System.out.println(b / x - removedNum);
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
}
//  [java]
import java.util.Scanner;
public class Main {
	public static void main(String[]  args) {
		Scanner input = new Scanner(System.in);	
		long a = input.nextLong();
        long b = input.nextLong();
        long x = input.nextLong();
        long count;
        if(b%x ==0 || a == x) {
        	count = Math.abs(b-a)/(x)+1;}
        else{
        	count = Math.abs(b-a)/(x);}
        System.out.println(count);
		   }			
		}
//  [java]
import java.util.Scanner;
public class Main {
	public static void main(String[]  args) {
		Scanner input = new Scanner(System.in);	
		long a = input.nextLong();
        long b = input.nextLong();
        long x = input.nextLong();
        long count;
        if(b%x !=0) {
           count = Math.abs(b-a)/(x);}
        else {
        count = Math.abs(b-a)/(x)+1;}
        System.out.println(count);
		   }			
		}
//  [java]
import java.util.*;
public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong();
		long b = sc.nextLong();
		long x = sc.nextLong();
		long res=0;
		if (b-a ==0) {
			res =0;
		}
		else {
			res = (b/x) - (a/x);
			if (a%x==0) {
				res++;}
			}
		
		System.out.println(res);
	}

}
//  [cpp]
#include<iostream>
using namespace std;

int main() {
	long long a, b, x; cin >> a >> b >> x;
	
	long long ans = 0;
	if (a == 0); else ans -= (a-1) / x + 1;
	ans += b / x + 1;
	cout << ans << endl;

	return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#include <iomanip>
#include <iostream>
using namespace std;
using ll = long long;
const long long INF = 1LL << 60;
 
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
ll max(ll a, ll b){
    if(a > b) return a;
    else return b;
}
 
ll min(ll a, ll b){
    if(a < b) return a;
    else return b;
}

int main(void){
    ll a,b; cin >> a >> b;
    ll x; cin >> x;
    if(b % x != 0) b = (b/x) * x;
    if(a % x != 0) a = (a/x + 1) * x;
    cout << max(b/x - a/x + 1, 0) << endl;
}
//  [cpp]
#include <iostream>

using namespace std;

int main()
{
    long long a,b,x,cnt=0;
    cin>>a>>b>>x;
    if ( a % x ==0)
        cout<<b/x-a/x+1<<endl;
    else
        cout<<b/x-a/x<<endl;
    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#define lln unsigned long long int
using namespace std;
int main()
{
    lln a,b,x;
    cin>>a>>b>>x;
    if(a>b)
        swap(a,b);
    if(a==b && a%x!=0)
    {
        cout<<0<<endl;
        return 0;
    }
    if(b==x)
    {
        cout<<1<<endl;
        return 0;
    }
    if(x>b)
    {
        cout<<0<<endl;
        return 0;
    }
    if(a==1 && x==1)
    {
        cout<<b<<endl;
        return 0;
    }
    if(x==1)
    {
        cout<<b-a+1<<endl;
        return 0;
    }
    lln ans=(b/x)-(a/x);
    if(a%x==0)
    {
        cout<<ans+1<<endl;
    }
    else
        cout<<ans<<endl;
}
//  [cpp]

/** author: __nishad__ **/
//#pragma GCC optimize(2)
//#pragma GCC optimize(3, "Ofast", "inline")
#include<bits/stdc++.h>
using namespace std;


typedef long long ll ;
typedef vector<ll> vll ;

#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define all(v) (v).begin(),(v).end()
#define precision(k) cout<<setprecision(k)<<fixed;
#define loop(i,a,b) for(ll i=(a);i<=(b);++i)
#define minv(v) *min_element(all(v))
#define maxv(v) *max_element(all(v))
#define getpos(v,x) (lower_bound(v.begin(),v.end(),x)-v.begin())
#define unq(v) sort(all(v)),(v).erase(unique((v).begin(),(v).end()),(v).end())
#define pb push_back
#define mp make_pair
#define pi 3.14159265358979323
#define endl "\n"

int main()
{
    IOS;


    unsigned long long a, b, x, count=0, diff;
    cin>>a>>b>>x;

    diff = b - a;

    count = diff/x;

    if(diff != 0){
        if(a%x == 0)
            count++;

        cout<<count;
    }
    else
        cout<<"0";


}
//  [c]
#include<stdio.h>
int main()
{
	long long int a,b,x;

	scanf("%lld%lld%lld",&a,&b,&x);

	if(a%x==0)
		printf("%lld",b/x-a/x+1);
	else
		printf("%lld",b/x-a/x);
	return 0;
}
//  [c]
#include <stdio.h>


int main()
{
    unsigned long int a, b, x, ans;
    
    scanf("%lu %lu %lu", &a, &b, &x);

    if ((a % x) == 0)
    {
	ans = (b / x) - (a / x) + 1;
    }
    else
    {
	ans = (b / x) - (a / x);
    }
    
    printf("%lu\n", ans);

    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

int main() {

    long a, b, x;
    scanf("%ld %ld %ld", &a, &b, &x);

    long cnt01 = b / x;
    long cnt02;

    if (a == 0) {
        cnt02 = 0;
        cnt01++;
    } else {
        cnt02 = (a - 1) / x;

    }

    

    printf("%ld", cnt01 - cnt02);

    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{

    long long a, b, x;
    long long count = 0;

    scanf("%lld %lld %lld", &a, &b, &x);

    long long ai = a / x;
    long long bi = b / x;

    long long start, goal;

    if (ai * x == a)
        start = ai;
    else
        start = ai + 1;

    goal = bi;

    printf("%d", goal - start+1);


    return 0;

}
//  [c]
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{

    long long a, b, x;
    long long count = 0;

    scanf("%lld %lld %lld", &a, &b, &x);

    long long ai = a / x;
    long long bi = b / x;

    long long start, goal;

    if (ai * x == a)
        start = ai;
    else
        start = ai + 1;

    goal = bi;

    printf("%d", goal - start);


    return 0;

}
//  [c]
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{

    long long a, b, x;
    long long count = 0;

    scanf("%lld %lld %lld", &a, &b, &x);

    if (a == 0)
        count = b / x + 1;
    else
        count = b / x - (a - 1) / x;

    printf("%d", count);

    return 0;

}
//  [javascript]
const D = 24;
const L = 3;

function new64(n) {
    return [n % (1<<D), (n / (1<<D)) | 0, 0];
}

function mul64s(a, b) {
    var r = [];
    var x = 0;
    for (var i = 0; i < L; i++) {
        x = a[i] * b + x;
        r[i] = x % (1<<D);
        x = Math.floor(x / (1<<D));
    }
    return r;
}

function add64s(a, b) {
    var r = [];
    var x = b;
    for (var i = 0; i < L; i++) {
        x = a[i] + x;
        r[i] = x % (1<<D);
        x = Math.floor(x / (1<<D));
    }
    return r;
}

function cmp64(a, b) {
    for (var i = L-1; i >= 0; i--) {
        if (a[i] < b[i]) return -1;
        if (a[i] > b[i]) return 1;
    }
    return 0;
}

function add64(a, b) {
    var r = [];
    var x = 0;
    for (var i = 0; i < L; i++) {
        x = a[i] + b[i] + x;
        r[i] = x % (1<<D);
        x = Math.floor(x / (1<<D));
    }
    return r;
}

function sub64(a, b) {
    var r = [];
    var x = 0;
    for (var i = 0; i < L; i++) {
        x = a[i] - b[i] - x;
        var borrow = 0;
        while (x < 0) {
            x += (1<<D);
            borrow++;
        }
        r[i] = x % (1<<D);
        x = borrow;
    }
    return r;
}

function div64s(a, b) {
    var x = 0;
    for (var i = L-1; i >= 0; i--) {
        x = a[i] + x * (1<<D);
        a[i] = (x / b) | 0;
        x = x % b;
    }
    return x;
}

function copy64(a, b) {
    for (var i = 0; i < L; i++) {
        a[i] = b[i];
    }
}

function shiftL64(a) {
    const msb = [0, 0, (1<<(D-1))];
    var d = a;
    var r = 0;
    if (cmp64(a, msb) >= 0) {
        r = 1;
        d = sub64(a, msb);
    }
    var c = add64(d, d);
    copy64(a, c);
    return r;
}

function div64(a, b) {
    var d = new64(0);
    var x = a.slice();
    var r = new64(0);
    for (var i = 0; i < L*D; i++) {
        var bit = shiftL64(x);
        shiftL64(d);
        d = add64s(d, bit);
        var y = 0;
        if (cmp64(d, b) >= 0) {
            d = sub64(d, b);
            y = 1;
        }
        shiftL64(r);
        r = add64s(r, y);
    }
    return r;
}

function parse64(s) {
    const l = s.length;
    var a = new64(0);
    for (var i = 0; i < l; i++) {
        a = mul64s(a, 10);
        a = add64s(a, parseInt(s.substr(i, 1), 10));
    }
    return a;
}

function print64(a) {
    var s = "";
    var x = a.slice();
    while (cmp64(x, new64(0)) !== 0) {
        s += div64s(x, 10);
    }
    if (s === "") {
        s = "0";
    }
    console.log(s.split('').reverse().join(''));
}

function divisors(a, x) {
    return add64s(div64(a, x), 1);
}

function solve(a, b, x) {
    return sub64(divisors(b, x), (cmp64(a, new64(1)) >= 0 ? divisors(sub64(a, new64(1)), x) : new64(0)));
}

function main(input) {
    const args = input.trim().split(' ');
    const a = parse64(args[0]);
    const b = parse64(args[1]);
    const x = parse64(args[2]);
    const c = solve(a, b, x);
    print64(c);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input) {
  input = input.trim()
  var [a,b,c] = input.split(" ").map(BigInt);
  console.log(((b/c)-(a==0?0n:a-1n)/c+((a==0n)?1n:0n)).toString())
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.trim()
  var [a,b,c] = input.split(" ").map(BigInt);
  console.log(((b/c)-(a==0?0n:a-1n)/c).toString())

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.trim()
  var [a,b,c] = input.split(" ").map(BigInt);
  console.log(((b/c)-(a==0?0:a-1n)/c).toString())

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.trim()
  var [a,b,c] = input.split(" ").map(BigInt);
  if(a==0)a=1n
  console.log(((b/c)-(a-1n)/c).toString())

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

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

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush()
	A, B, K := nextInt(), nextInt(), nextInt()
	AV, BV := A/K, B/K
	if A%K == 0 {
		AV--
	}
	fmt.Fprintln(out, BV-AV)
}

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

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func chars(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}
//  [go]
package main

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

var sc = bufio.NewScanner((os.Stdin))

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

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

func main() {
	sc.Split(bufio.ScanWords)
	a, b, x := nextInt(), nextInt(), nextInt()

	fmt.Printf("%d\n", ABC048B(a, b, x))
}

// ABC048B ...
func ABC048B(a, b, x int) (res int) {
	if a == 0 {
		res++
	}
	res += b/x - (a-1)/x

	return
}
//  [go]
package main

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

var sc = bufio.NewScanner((os.Stdin))

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

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

func main() {
	sc.Split(bufio.ScanWords)
	a, b, x := nextInt(), nextInt(), nextInt()

	fmt.Printf("%d\n", ABC048B(a, b, x))
}

// ABC048B ...
func ABC048B(a, b, x int) int {
	return b/x - (a-1)/x
}
//  [go]
package main

import "fmt"

func main() {
	// Code for B - Between a and b ...
	var a, b, x int
	fmt.Scanf("%d %d %d", &a, &b, &x)

	ans := (b/x + 1) - ((a-1)/x + 1)
	fmt.Println(ans)
}
//  [ruby]
a, b, x = gets.split.map(&:to_i)
s, t = a.divmod(x)
puts b / x - s + (t == 0 ? 1 : 0)
//  [ruby]
a, b, x = gets.chomp.split.map(&:to_i)
lb = (a + x - 1) / x * x
ub = b / x * x
puts (lb > b || ub < a)? "0" : (ub - lb) / x + 1
//  [ruby]
a, b, x = gets.chomp.split.map(&:to_i)

num_a = (a - 1) / x
num_b = b / x

if 0 < a
  puts num_b - num_a
else
  puts num_b + 1 # 個数を見ている
end
//  [ruby]
a,b,x = gets.split.map(&:to_i)

l = a / x
m = b / x
if l % x == 0
  puts m - l + 1
else
  puts m - l
end
//  [ruby]
a,b,x = gets.split.map(&:to_i)

puts b / x - [0, a - 1].max / x
//  [ruby]
a,b,x = gets.split.map(&:to_i)

puts b / x - [0, a - 1].min / x
//  [rust]
// Your code here!
use std::io::*;
use std::str::FromStr;

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 read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}



fn main(){
    let nums:Vec<i64> = read_vec();
    let mut a:i64 = nums[0];
    let mut b:i64 = nums[1];
    let mut x:i64 = nums[2];
    
    println!("{}",b/x-a/x + (if a%x==0 {1} else {0}));
    
    
}
//  [rust]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(unused_imports)]

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

struct Scanner<I: Iterator<Item = char>> {
    iter: std::iter::Peekable<I>,
}

macro_rules! exit {
    () => {{
        exit!(0)
    }};
    ($code:expr) => {{
        if cfg!(local) {
            writeln!(std::io::stderr(), "===== Terminated =====")
                .expect("failed printing to stderr");
        }
        std::process::exit($code);
    }}
}

impl<I: Iterator<Item = char>> Scanner<I> {
    pub fn new(iter: I) -> Scanner<I> {
        Scanner {
            iter: iter.peekable(),
        }
    }

    pub fn safe_get_token(&mut self) -> Option<String> {
        let token = self.iter
            .by_ref()
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        if token.is_empty() {
            None
        } else {
            Some(token)
        }
    }

    pub fn token(&mut self) -> String {
        self.safe_get_token().unwrap_or_else(|| exit!())
    }

    pub fn get<T: FromStr>(&mut self) -> T {
        self.token().parse::<T>().unwrap_or_else(|_| exit!())
    }

    pub fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
        (0..len).map(|_| self.get()).collect()
    }

    pub fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
        (0..row).map(|_| self.vec(col)).collect()
    }

    pub fn char(&mut self) -> char {
        self.iter.next().unwrap_or_else(|| exit!())
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.get::<String>().chars().collect()
    }

    pub fn mat_chars(&mut self, row: usize) -> Vec<Vec<char>> {
        (0..row).map(|_| self.chars()).collect()
    }

    pub fn line(&mut self) -> String {
        if self.peek().is_some() {
            self.iter
                .by_ref()
                .take_while(|&c| !(c == '\n' || c == '\r'))
                .collect::<String>()
        } else {
            exit!();
        }
    }

    pub fn peek(&mut self) -> Option<&char> {
        self.iter.peek()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin.bytes().map(|c| c.unwrap() as char));
    let a: usize = sc.get();
    let b: usize = sc.get();
    let x: usize = sc.get();
    let ans;
    if a > 0 {
        ans = b / x - (a-1) / x;
    } else {
        ans = b / x + 1;
    }
    println!("{}", ans);
}
//  [rust]
use std::io;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<u64> = procon_read();
	let a = v[0];
	let b = v[1];
	let x = v[2];
	if a == 0 {
		println!("{}", b/x + 1);
	}else{
		println!("{}", b/x + 1 - (a - 1)/x - 1);
	}
}
//  [rust]
fn main() {
    proconio::input! {
    a:isize,
    b:isize,
    c:isize,
    }
    println!("{}",b/c-(a-1)/c)
}
//  [rust]
use proconio::input;

fn main() {
    input! {
        a: i64,
        b: i64,
        x: i64,
    };
    let x_a = (a - 1) / x;
    let x_b = b / x;
    let ans = x_b - x_a;
    println!("{}", ans);
}
//  [rust]
use std::io;

fn main() {
    let mut input_line:String = String::new();
    io::stdin().read_line(&mut input_line).expect("err");

    let inputs: Vec<&str> = input_line.split_whitespace().collect();

    let a = inputs[0].parse::<i64>().unwrap();
    let b = inputs[1].parse::<i64>().unwrap();
    let x = inputs[2].parse::<i64>().unwrap();

    let mut ans: i64 = f(b, x)-f(a-1, x);

    print!("{}", ans);
}

fn f(n: i64, x: i64) -> i64 {
   if n == -1{
       return -1;
   }else{
       return (n/x)+1;
   }
}
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (a, b, x) = (input[0], input[1], input[2])
print(b/x-(a>0 ?(a-1)/x:-1))
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (a, b, x) = (input[0], input[1], input[2])
print(a>0 ?b/x-(a-1)/x:b/x+1)
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (a, b, x) = (input[0], input[1], input[2])
print(b/x-(a-1)/(a>0 ?x:1))
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (a, b, x) = (input[0]-1, input[1], input[2])
print(a>0 ?b/x-a/x:b/x+1)
//  [swift]
extension String: CollectionType {
    func toInts() -> [Int] {
        return self.split(" ").map {Int($0)!}
    }
    
    func toUInts() -> [UInt64] {
        return self.split(" ").map {UInt64($0)!}
    }
    
    func toStrings() -> [String] {
        return self.split(" ")
    }
}

let values = readLine()!.toUInts()
let a = values[0]
let b = values[1]
let x = values[2]

let adjust: UInt64 = a % x == 0 ? 1 : 0

print((b - a) / x + adjust)
//  [swift]


extension String: CollectionType {
    func toInts() -> [Int] {
        return self.split(" ").map {Int($0)!}
    }
    
    func toUInts() -> [UInt] {
        return self.split(" ").map {UInt($0)!}
    }
    
    func toStrings() -> [String] {
        return self.split(" ")
    }
}

let values = readLine()!.toUInts()
let a = values[0]
let b = values[1]
let x = values[2]

let adjust: UInt = a % x == 0 ? 1 : 0

print((b - a) / x + adjust)
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const [a, b, x] = input[0].map(BigInt);

  if (a === 0n) {
    return (b / x + 1n).toString();
  } else {
    return (b / x - (a - 1n) / x).toString();
  }
};

console.log(main(read()));
//  [typescript]
{
  const Main = input => {
    const [a,b,x] = input.trim().split(" ").map(BigInt)
    console.log((b / x - (a - 1n) / x).toString())
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [typescript]
{
  const Main = input => {
    const [a,b,x] = input.trim().split(" ").map(v => BigInt(v))
    console.log(b / x - (a - 1n) / x)
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const [a, b, x] = input[0].map(BigInt);

return (b / x - (a - 1n) / x).toString();
};

console.log(main(read()));
//  [python]
N = int(input())
B = list(map(int, input().split()))

A = []
A.append(B[0])
for i in range(1, N-1):
    A.append(min(B[i], B[i-1]))
A.append(B[N-2])

print(sum(A))
//  [python]
import math

def main():
    n = int(input())
    B = list(map(int, input().split()))

    ans = B[0]+B[-1]
    for i in range(n-2):
        ans += min(B[i],B[i+1])
    print(ans)




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

res = Bs[0] + Bs[-1]
for i in range(N-2):
    res += min(Bs[i], Bs[i+1])

print(res)
//  [python]
n = int(input())
bn = [int(num) for num in input().split()]

an = [0]*n
an[0] = bn[0]
an[n-1] = bn[n-2]
for i in range(1,n-1):
    s = min(bn[i],bn[i-1])
    an.append(s)
    
print(sum(an))
print(an)
//  [python]
n=int(input())
b=list(map(int,input().split()))

ans=0
for i in range(n-1):
  if i == n-2:
    ans+=b[n-2]
  else:
    ans+=min(b[i],b[i+1])

print(ans)
//  [python]
n = int(input())
b = [int(i) for i in input().split()]

a =[b[0]]

for x in range(n-1):
  s = min(b[x],b[x+1])
  a.append(s)
  
a.append(b[-1])

print(sum(a))
//  [java]
import java.util.*;
import java.io.*;
import static java.lang.System.*;

class FastScanner {
  private final InputStream in = System.in;
  private final byte[] buffer = new byte[1024];
  private int ptr = 0;
  private int buflen = 0;
  private 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;
  }
  private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
  private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
  public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
  public 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();
  }
  public 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();
      }
  }
  public int nextInt() {
      long nl = nextLong();
      if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
      return (int) nl;
  }
  public double nextDouble() { return Double.parseDouble(next());}
}

class Main {
  public static final int MOD = 1000000007;
  public static final int INF = 1000000000;
  public static void main(String[] args) {
    FastScanner sc = new FastScanner();
    int N = sc.nextInt();
    int B[] = new int[N-1];
    for(int i=0; i<N-1; i++) B[i] = sc.nextInt();
    int ans = B[N-2];
    for(int i=N-2; i>0; i--){
      ans += Math.min(B[i], B[i-1]);
    }
    ans += B[0];
    out.println(ans);
  }
}
//  [java]
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int[] b = new int[n-1];
        for(int i=0; i<n-1; i++){
            b[i] = sc.nextInt();
        }

        int[] a  = new int[n];
        a[0] = b[0];
        for(int i=0; i<n-2; i++){
            a[i+1] = Math.min(b[i], b[i+1]);
        }
        a[n-1] = b[n-2];

        long ans = 0;
        for(int i=0; i<n; i++){
            ans += a[i];
        }

        System.out.println(ans);
    }

    private static class FastScanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;
        private 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;
        }
        private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
        private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
        public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
        public 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();
        }
        public 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();
            }
        }
        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
            return (int) nl;
        }
        public double nextDouble() { return Double.parseDouble(next());}
    }
}
//  [java]

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();

        int[] B = new int[N];

        for (int i = 0 ; i < N - 1 ; i++) {
            B[i] = scanner.nextInt();
        }

        long answer = B[0];

        for (int i = 1 ; i < N ; i++) {
            answer += Math.min(B[i], B[i - 1]);
        }

        System.out.println(answer);
    }
}
//  [java]
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws FileNotFoundException {

		//    	File file = new File("src/in.txt");
		//    	Scanner sc = new Scanner(file);

		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		int[] B = new int[N-1];
		for(int i=0;i<N-1;i++) {
			B[i]=sc.nextInt();
		}
		sc.close();
		if(N==1) {
			System.out.println(2*B[0]);
		} else {
			int ans = 0;
			for(int i=0;i<=N-3;i++) {
				ans += Math.min(B[i], B[i+1]);
			}
			ans += B[N-2];
			System.out.println(ans);
		}
	}
}
//  [cpp]
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0' && ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int stack[20];
inline void write(int x)
{
	if(x<0){putchar('-');x=-x;}
    if(!x){putchar('0');return;}
    int top=0;
    while(x)stack[++top]=x%10,x/=10;
    while(top)putchar(stack[top--]+'0');
}
inline void pr1(int x){write(x),putchar(' ');}
inline void pr2(int x){write(x),puts("");}
int main()
{
    //freopen("a.in","r",stdin);
	//freopen("a.out","w",stdout);
	int n=read(),ans=0,uf=100001;
	for(int i=1;i<n;i++)
	{
		int d=read();
		ans+=min(uf,d);uf=d;
	}pr2(ans+uf);
    return 0;
}
//  [cpp]
#include<stdio.h>
 
int main(void) {
  
  int N,B[100];
  
  //標準入力
  scanf("%d", &N);
  for(int i = 0; i < N - 1; i++)  {
    scanf("%d", &B[i]);
  }
  
  //Aの要素の総和の最大値sumを求める
  int sum = 0;
  sum += B[0];
  for(int i = 0; i < N - 2; i++) {
    if (B[i] <= B[i+1]) {
      sum += B[i];
    } else {
      sum += B[i+1];
    }
  }
  sum += B[N-2];
  
  //出力
  printf("%d\n", sum);
  
  return 0;
  
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i,a) for(int i=0;i<int(a);++i)
#define REP(i,a,b) for(int i=int(a);i<int(b);++i)
#define pb push_back
#define mp make_pair
#define F first
#define S second
using ll = long long;
using itn = int;
using namespace std;
static const long double GRATIO=(long double)(1+sqrt(5))/2;
ll GCD(ll a, ll b){
    return b ? GCD(b, a%b) : a;
}
ll LCM(ll a, ll b){
    return a/GCD(a,b)*b;
}
int main(){
    int N;
    cin>>N;
    vector<int> B(N-1);
    rep(i,N-1) cin>>B.at(i);
    vector<int> A(N);
    ll ans=0;
    rep(i,N){
        if(i==0) A.at(i)=B.at(i);
        if(0<i && i<N-1) A.at(i)=min(B.at(i-1),B.at(i));
        if(i==N-1) A.at(i)=B.at(i-1);
    }
    rep(i,N) ans+=A.at(i);
    cout<<ans<<endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
	int n;
	cin>>n;
	vector<int>arr(n);
	for(int i=1; i<n; i++)
	 cin>>arr[i];
	for(int i=2; i<n-1; i++){
		if(arr[i]>arr[i-1] && arr[i]>arr[i+1])
		 arr[i]=max(arr[i+1],arr[i-1]);
	}
	vector<int>ans(n+1);
	ans[1]=arr[1];
	for(int i=2; i<=n; i++){
		ans[i]=arr[i-1];
	}
	int sum=0;
	for(int i=1; i<=n; i++)
	 sum+=ans[i];
	cout<<sum;
	return 0;
	
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
int main(){
  int n;
  int ans,bmax;
  vector<int>a(110,2e5),b(110);
  cin>>n;
  for(int i=0;i<n-1;i++)cin>>b[i];
  for(int i=1;i<n-1;i++)ans=min(b[i],b[i-1]);
  ans+=b[n-2]+b[0];
  cout<<ans<<endl;
  return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
int main(){
  int n;
  int ans,bmax;
  vector<int>a(110,2e5),b(110);
  cin>>n;
  for(int i=0;i<n-1;i++)cin>>b[i];
  for(int i=1;i<n-1;i++)ans=min(b[i],b[i+1]);
  ans+=b[n-2]+b[0];
  cout<<ans<<endl;
  return 0;
}
//  [c]
#include<stdio.h>

int return_min(int a,int b)
{
  if(a>b){
    return b;
  }else{
    return a;
  }
}

int main(void)
{
  int n;
  scanf("%d",&n);
  int a[n];
  int b[n-1];
  for(int i=0;i<n-1;i++){
    scanf("%d",&b[i]);
  }
  a[0]=b[0];
  a[n-1]=b[n-2];
  for(int i=1;i<n-1;i++){
    a[i]=return_min(b[i-1],b[i]);
  }
  int result=0;
  for(int i=0;i<n;i++){
    result+=a[i];
  }
  printf("%d\n",result);
  return 0;
}
//  [c]
int main()
{
  int n;
  scanf("%d", &n);
  int b[n - 1], i;
  for (i = 0; i < n - 1; i++)
    scanf("%d", &b[i]);
  int a[i];
  for (i = 0; i < n - 1; i++)
  {
    if (i == 0)
    {
      a[i] = b[i];
      a[i + 1] = b[i];
    }
    else if (i != 0)
    {
      if (a[i] > b[i])
        a[i] = b[i];
      a[i + 1] = b[i];
    }
  }
  int sum = 0;
  for (i = 0; i < n; i++)
    sum += a[i];
  printf("%d", sum);
}
//  [c]
#include <stdio.h>

int main(void) {
    int n, i, ans;
    scanf("%d", &n);
    int b[n-1];

    for (i = 0; i < n - 1; i++) {
        scanf("%d", &b[i]);
    }
    ans = b[0] + b[n - 2];
    
    for (i = 1; i < n - 1; i++) {
        if (b[i-1] < b[i]) ans += b[i - 1];
        else ans += b[i];
    }

    printf("%d\n", ans);
}
//  [c]
#include<stdio.h>
int min(int a,int b){
  if(a<=b){
    return a;
  }
  else {
    return b;
  }
}


int main(){
  int N;
  scanf("%d",&N);
  int b[N-1];
  int a[N];
  
  for (int i=0;i<=N-1;i++){
    scanf("%d",&b[i]);
  }
  
  a[0]=b[0];
  
  for (int i=1;i<=n-2;i++){
    a[i]=min(b[i],b[i-1]);
  }
  
  a[N-1]=b[N-2];
  
  int ans=0;
  for (int i=0;i<N;i++){
    ans+=a[i];
  }
  
  printf("%d",ans);
  
  return 0;
}
//  [c]
#include<stdio.h>

int main(void){
  int n;
  scanf("%d",&n);

  int a[n] , b[n-1];
  for(int i = 0;i < n-1;i ++){
    scanf("%d",&b[i]);
  }

  int ans = b[0];
  for(int i = 0;i < n-1;i ++){
    if(b[i] <= b[i+1]){
      ans += b[i];
    }
    else{
      ans += b[i+1];
    }
  }

  printf("%d\n",ans);

  return  0;
 
}
//  [c]
#include <stdio.h>

int main()
{
	int i, N, B[100];
	scanf("%d", &N);
	for (i = 1; i < N; i++) scanf("%d", &(B[i]));
	
	int sum = B[1];
	for (i = 1; i < N; i++) {
		if (B[i] < B[i+1]) sum += B[i];
		else sum += B[i+1];
	}
	
	printf("%d\n", sum);
	fflush(stdout);
	return 0;
}