jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]

/// Swift5 -> Swift2.2

extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
extension Array where Element: Comparable {
    // sorted()
    func sorted() -> [Element] {
        return self.sort( { $0 < $1 } )
    }
}
// stride(from:through:by:)
func stride(from start: Int, through end: Int, by stride: Int) -> StrideThrough<Int> {
    return start.stride(through: end, by: stride)
}
// stride(from:to:by)
func stride(from start: Int, to end: Int, by stride: Int) -> StrideTo<Int> {
    return start.stride(to: end, by: stride)
}
extension Range {
    func reversed() -> [Element] {
        return self.reverse()
    }
}

/// end

let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let W = input[1]

var dp = Array(repeating: 0, count: W + 1)

for _ in 0 ..< N {
    let knapsack = readLine()!.split(separator: " ").map { Int($0)! }
    let weight = knapsack[0]
    let value = knapsack[1]

  	let tmp = (weight ... W).reverse()
    for i in stride(from: W, through: weight, by: -1) {
        dp[i] = max(dp[i], dp[i - weight] + value)
    }
}

print(dp.last!)
//  [python]
#gcdは3.4.3だとfractionsにある
from fractions import gcd

from math import factorial as f

from math import ceil,floor,sqrt

from sys import exit

from copy import deepcopy
import numpy as np

import bisect
import re


ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))



def main():
    n = ii()

    a = li()
    b = li()
    c = li()

    ans = 0

    for i in range(n):
        ans+=b[i]

    for i in range(n-1):
        if a[i+1] == a[i]+1:
            ans+=c[a[i]-1]

    print(ans)


main()
//  [python]
import bisect
import heapq
import itertools
import math
import operator
import os
import re
import string
import sys
from collections import Counter, deque, defaultdict
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from functools import lru_cache, reduce
from operator import itemgetter, mul, add, xor

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))
B = list(map(int, sys.stdin.readline().split()))
C = list(map(int, sys.stdin.readline().split()))

ans = 0
for i in A:
    ans += B[i - 1]

for i, j in zip(A, A[1:]):
    if i + 1 == j:
        ans += C[i - 1]

print(ans)
//  [python]
# coding: utf-8
import sys
# import random
# import bisect
# import math
import numpy as np
# from fractions import gcd
# import itertools

"""Template"""


class IP:
    """
    入力を取得するクラス
    """

    def __init__(self):
        self.input = sys.stdin.readline

    def I(self):
        """
        1文字の取得に使います
        :return: int
        """
        return int(self.input())

    def S(self):
        """
        1文字の取得(str
        :return: str
        """
        return self.input()

    def IL(self):
        """
        1行を空白で区切りリストにします(int
        :return: リスト
        """
        return list(map(int, self.input().split()))

    def SL(self):
        """
        1行の文字列を空白区切りでリストにします
        :return: リスト
        """
        return list(map(str, self.input().split()))

    def ILS(self, n):
        """
        1列丸々取得します(int
        :param n: 行数
        :return: リスト
        """
        return [int(self.input()) for _ in range(n)]

    def SLS(self, n):
        """
        1列丸々取得します（str
        :param n: 行数
        :return: リスト
        """
        return [self.input() for _ in range(n)]

    def SILS(self, n):
        """
        Some Int LineS
        横に複数、縦にも複数
        :param n: 行数
        :return: list
        """
        return [self.IL() for _ in range(n)]

    def SSLS(self, n):
        """
        Some String LineS
        :param n: 行数
        :return: list
        """
        return [self.SL() for _ in range(n)]


class Idea:
    def __init__(self):
        pass

    def S(self, s, r=0, m=-1):
        """
        ソート関係行います。色々な設定あります。
        :param s: 元となるリスト
        :param r: reversするかどうか 0=False 1=True
        :param m: （2次元配列）何番目のインデックスのソートなのか
        :return: None
        """
        r = bool(r)
        if m == -1:
            s.sort(reverse=r)
        else:
            s.sort(reverse=r, key=lambda x: x[m])

    def ceil(self, x, y):
        """
        Round up
        小数点切り上げ割り算
        :param x: int
        :param y: int
        :return: int
        """
        return -(-x // y)

    def ave(self, a):
        """
        平均を求めます
        :param a: list
        :return: int
        """
        return sum(a) / len(a)

    def gcd(self, x, y):
        if y == 0:
            return x
        else:
            return self.gcd(y, x % y)

    def lcm(self, x, y):
        return (x * y) // self.gcd(x, y)


"""ここからメインコード"""


def make_divisors(n):
    # divisors = []
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            # divisors.append(i)
            return i
            # if i != n // i:
            #     divisors.append(n//i)


def n_to_10(X, n):
    if int(X / n):
        return n_to_10(int(X / n), n) + str(X % n)
    return str(X % n)


def main():
    ip = IP()
    id = Idea()
    """この下から書いてね"""
    n = int(input())
    a = ip.IL()
    b = ip.IL()
    c = ip.IL()
    memo = a[0]
    ans = 0
    for i in range(1, n):
        if memo + 1 == a[i]:
            ans += c[memo-1]
        memo = a[i]
        # print(i, ans)
    print(sum(b) + ans)


main()
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		try (Scanner sc = new Scanner(System.in)) {
			int N = Integer.parseInt(sc.nextLine());
			int[] A = Arrays.stream(sc.nextLine().split(" ")).mapToInt(r -> Integer.parseInt(r)).toArray();
			int[] B = Arrays.stream(sc.nextLine().split(" ")).mapToInt(r -> Integer.parseInt(r)).toArray();
			int[] C = Arrays.stream(sc.nextLine().split(" ")).mapToInt(r -> Integer.parseInt(r)).toArray();

			int sum = 0;
			for (int i = 0; i < N; i++) {
				sum += B[A[i] - 1];
				if (i > 0 && A[i - 1] + 1 == A[i]) {
					sum += C[A[i - 1] - 1];
				}
			}
			System.out.println(sum);
		}
	}
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int N=Integer.parseInt(sc.nextLine());
		Integer[] A=Arrays.asList(sc.nextLine().split(" "))
				.stream().map(Integer::valueOf).toArray(Integer[]::new);
		Integer[] B=Arrays.asList(sc.nextLine().split(" "))
				.stream().map(Integer::valueOf).toArray(Integer[]::new);
		Integer[] C=Arrays.asList(sc.nextLine().split(" "))
				.stream().map(Integer::valueOf).toArray(Integer[]::new);
		int result=0;
		for(int i=0;i<N;i++) {
			result+=B[A[i]-1];
			if(i<(N-1)&&A[i+1]==A[i]+1) {
				result+=C[A[i]-1];
			}
		}
		System.out.println(result);
	}
}
//  [java]
import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int ans = 0;
		int[] A = new int[N];
		int[] C = new int[N-1];
		Arrays.setAll(A, i->sc.nextInt());
		
		for (int i=0; i<N; i++) {
			ans += sc.nextInt();
		}
		
		Arrays.setAll(C, i->sc.nextInt());
		
		for (int i=0; i<N-1; i++) {
			if (A[i]+1 == A[i+1]) {
				ans += C[A[i]-1];
			}
		}
		System.out.println(ans);
	}
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define fastio 			ios::sync_with_stdio(0);	cin.tie(0); cout.tie(0);  cout<<fixed;  cout<<setprecision(12);
#define randomINT 		mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define	newl 			cout<<"\n"
#define DISP(as)		for(auto it : as) cout<<it<<" ";newl;
#define all(x)         	(x).begin(),(x).end()
#define mset(x,val)    	memset(x,val,sizeof(x))
#define newl           	cout<<"\n"
#define pb             	push_back
#define mp             	make_pair
#define f 				first
#define s 				second
#define dline          cerr<<"///REACHED///\n";
#define deb1(x)        cerr<<#x<<" = "<<x<<'\n';
#define deb2(x,y)      cerr<<'['<<#x<<','<<#y<<"] = "<<'['<<x<<','<<y<<']'<<'\n';
#define deb3(x,y,z)    cerr<<'['<<#x<<','<<#y<<','<<#z<<"] = "<<'['<<x<<','<<y<<','<<z<<']'<<'\n';

typedef long long 				ll;
typedef long double 			ld;
typedef vector<ll> 				vll;
typedef pair<ll , ll> 			pll;
typedef pair<ld, ld> 			pld;
typedef unordered_map<ll, ll> 	um;
typedef vector<pll> 			vpll;

const ll 	MAX5 	= 	1e+5 + 7;
const ll 	MAX7 	= 	1e+7 + 7;
const ll 	MAXN 	= 	MAX7;
const ll   	INF   	=  	0x7f7f7f7f7f7f7f7f;
const int  	INFi 	=  	0x7f7f7f7f;
const ll 	MOD		=  	1e+9 + 7;

vll adj[MAXN]; ll visit[MAXN] = {};
int dx8[] = {0, 1, 1, 1, 0, -1, -1, -1}, dy8[] = {1, 1, 0, -1, -1, -1, 0, 1};
int dx4[] = {0, 1, 0, -1}, dy4[] = {1, 0, -1, 0};

// <------------- Declare Variables Here ------------> //

ll T = 1;
ll n, x, y, r, p;
string s, t;
// <------------- Implement Functions Here ----------> //



// <------------- Start of main() -------------------> //

void MAIN() {
	cin >> n;
	vll a(n+1),b(n+1),c(n);

	for(ll i=1;i<=n;i++) cin>>a[i];
	for(ll i=1;i<=n;i++) cin>>b[i];
	for(ll i=1;i<n;i++) cin>>c[i];

	ll sum = accumulate(all(b),0);
	
	for(ll i=2;i<=n;i++) {
		if(a[i]-1 == a[i-1]) {
			sum += c[a[i-1]];
		}
	}

	cout<<sum;
}

int main() {
	fastio; randomINT;
	//cin>>t;
	while (T--) {
		MAIN();
	}
	return 0;
}
//  [cpp]
// #define DEBUGGING
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define ALL(V) (V).begin(), (V).end()
#define ALLR(V) (V).rbegin(), (V).rend()

template <typename T> using V = vector<T>;
template <typename T> using VV = V<V<T>>;
using ll = int64_t;
using ull = uint64_t;
using PLL = pair<ll, ll>;

template <typename T> const T& var_min(const T &t) { return t; }
template <typename T> const T& var_max(const T &t) { return t; }
template <typename T, typename... Tail> const T& var_min(const T &t, const Tail&... tail) { return min(t, var_min(tail...)); }
template <typename T, typename... Tail> const T& var_max(const T &t, const Tail&... tail) { return max(t, var_max(tail...)); }
template <typename T, typename... Tail> void chmin(T &t, const Tail&... tail) { t = var_min(t, tail...); }
template <typename T, typename... Tail> void chmax(T &t, const Tail&... tail) { t = var_max(t, tail...); }
template <typename T> const T& clamp(const T &t, const T &low, const T &high) { return max(low, min(high, t)); }
template <typename T> void chclamp(T &t, const T &low, const T &high) { t = clamp(t, low, high); }

namespace init__ {

struct InitIO {
    InitIO() {
        cin.tie(nullptr);
        ios_base::sync_with_stdio(false);
        cout << fixed << setprecision(30);
    }
} init_io;

}

#ifdef DEBUGGING
// #include "../debug/debug.cpp"
#include "../../debug/debug.cpp"
#else
#define DEBUG(...) 0
#define DEBUG_SEPARATOR_LINE 0
#endif

template <typename T>
T make_v(T init) { return init; }

template <typename T, typename... Tail>
auto make_v(T init, size_t s, Tail... tail) {
#define rec make_v(init, tail...)
    return V<decltype(rec)>(s, rec);
#undef rec
}

void input(V<ll> &v) { for(auto &&ele : v) cin >> ele; }

int main() {
    ll N;
    cin >> N;
    V<ll> A(N), B(N), C(N - 1);
    input(A);
    input(B);
    input(C);
    for(auto &&ele : A) ele--;
    ll ans = 0;
    ll pre = -2;
    for(ll i = 0; i < N; i++) {
        ans += B[A[i]];
        if(pre + 1 == A[i]) ans += C[pre];
        pre = A[i];
    }
    cout << ans << endl;
    return 0;
}
//  [c]
#include<stdio.h>
int main()
{
  int n,i,sum;
  sum=0;
  scanf("%d",&n);
  
  int a[n],b[n],c[n];
  for(i=0;i<n;++i)
  {scanf("%d",&a[i]);}
  
  for(i=0;i<n;++i)
  {scanf("%d",&b[i]);
  sum=sum+b[i];
  }
  
  for(i=0;i<n;++i)
  {scanf("%d",&c[i]);
  }
  
  for(i=0;i<n;++i)
  {
  if(a[i+1]-a[i]==1) sum=sum+c[a[i]-1];  
  }
  
  printf("%d",sum);
return 0;  
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int n;
  int i;
  int ans = 0;
  
  scanf("%d", &n);

  int a[n];
  int b[n];
  int c[n-1];

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

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

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

  for(i = 0; i < n; i++) {
    ans += b[a[i]];
    if(i != 0) {
      if((a[i] - a[i-1] == 1)) {
	ans += c[a[i-1]];
      }
    }
  }

  printf("%d\n", ans);
  
  return(0);
}
//  [c]
#include <stdio.h>

int main(void){
	int n;
	scanf("%d", &n);
	int *a = malloc(sizeof(int) * n)
		, *b = malloc(sizeof(int) * n)
		, *c = malloc(sizeof(int) * n);
	for(int i = 0; i < n; i++)
		scanf("%d", a + i);
	for(int i = 0; i < n; i++)
		scanf("%d", b + i);
	for(int i = 0; i < n - 1; i++)
		scanf("%d", c + i);
	int sum = 0;
	for(int i = 0; i < n; i++)
		sum += b[a[i] - 1];
	for(int i = 0; i < n - 1; i++)
		if(a[i] + 1 == a[i + 1])sum += c[a[i] - 1];
	printf("%d\n", sum);
	return 0;
}
//  [javascript]
'use strict';
const main = val => {
  const n = parseInt(val[0], 10);
  const a = val[1].split(' ').map(p => parseInt(p, 10));
  const b = val[2].split(' ').map(p => parseInt(p, 10));
  const c = val[3].split(' ').map(p => parseInt(p, 10));
  var ans = 0;
  b.map(val => ans += val);
  for (let i = 0; i < a.length - 1; i++) {
    ans += a[i+1]-a[i] == 1 ? c[a[i]-1] : 0;
  }
  console.log(ans);
}
main(require("fs").readFileSync("/dev/stdin", "utf8").split('\n'));
//  [javascript]
const lineList = require('fs').readFileSync('/dev/stdin','utf8').trim().split('\n')

const n = parseInt(lineList[0])
const a = lineList[1].split(' ').map(e => parseInt(e) - 1)
const b = lineList[2].split(' ').map(e => parseInt(e))
const c = lineList[3].split(' ').map(e => parseInt(e))

var scores = 0
var lastTimeMenu = 19 // init value is except (-1 <= lastTimeMenu <= 18)
for(var i=0;i<a.length;i++) {
  scores += b[a[i]]

  if(lastTimeMenu+1 === a[i]) {
    scores += c[lastTimeMenu]
  }

  lastTimeMenu = a[i]
}

console.log(scores)
//  [javascript]
input = require("fs").readFileSync("/dev/stdin", "utf8")

lines = input.split("\n")
N = lines.shift() * 1
A = lines.shift().split(' ').map(function(i) { return i * 1 })
B = lines.shift().split(' ').map(function(i) { return i * 1 })
C = lines.shift().split(' ').map(function(i) { return i * 1 })

ans = 0
for (i = 0; i < N; i++) {
    ans += B[A[i] - 1]
    if (i > 0) {
        if (A[i] - A[i-1] == 1) {
            ans += C[A[i-1] - 1]
        } 
    }
}

console.log(ans)
//  [go]
package main
 
import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
)
 
func run() {
	n := nextInt()
	
	v := make([]int, 0)
	l := make([]int, 0)
	k := make([]int, 0)
	
	for i := 0; i < n; i++ {
		v = append(v, nextInt())
	}
	for i := 0; i < n; i++ {
		l = append(l, nextInt())
	}
	for i := 0; i < n-1; i++ {
		k = append(k, nextInt())
	}
	
	last := -2
	answer := 0
	for i := 0; i < n; i++ {
		answer += l[v[i]-1]
		if( last == v[i]-1 ){
			answer += k[v[i]-2]
		}
		last = v[i]
	} 	
	Println(answer)
}
 
// --- template ---
// Thanks https://gist.github.com/halllllll/853ab587fd82ee3ffe6f7fb7fb499695
 
var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)
 
// Caution: You will get unexpected result if a single token is larger than this size.
const BufferSize = 64 * 1024 * 1024
 
func Print(a ...interface{}) (n int, err error) {
	return fmt.Fprint(out, a...)
}
 
func Printf(format string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, format, a...)
}
 
func Println(a ...interface{}) (n int, err error) {
	return fmt.Fprintln(out, a...)
}
 
func next() string {
	sc.Scan()
	return sc.Text()
}
 
func nextInt() int {
	a, err := strconv.Atoi(next())
	if err != nil {
		log.Fatal(err)
	}
	return a
}
 
func nextFloat() float64 {
	a, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		log.Fatal(err)
	}
	return a
}
 
func main() {
	sc.Buffer(make([]byte, 0, BufferSize), BufferSize)
	sc.Split(bufio.ScanWords)
	run()
	out.Flush()
}
//  [ruby]
n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)
c = gets.chomp.split(" ").map(&:to_i)
arr = []
count = 0
while true
    point = a.shift
    count += b[point - 1]
    if arr[-1] == point - 1
        count += c[point - 2]
    end
    arr << point
    if a == []
        break
    end
end
puts count
//  [ruby]
n=gets.to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
c=gets.split.map &:to_i
ans=b.sum
for i in 0..n-2
if a[i]+1 ==a[i+1]
  ans+=c[a[i]-1]
end
end
puts ans
//  [ruby]
input = readlines()

n = input.shift.chomp.to_i
al = input.shift.chomp.split("\s").map{|x| x.to_i}
bl = input.shift.chomp.split("\s").map{|x| x.to_i}
cl = input.shift.chomp.split("\s").map{|x| x.to_i}

sum = 0
al.each_with_index do |d, i|
  di = d - 1
  sum += bl[di]
  if i > 0 && d == al[i - 1] + 1
    sum += cl[di - 1]
  end
end

puts sum
//  [rust]
#[allow(unused_imports)]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input!(n: usize, a: [usize; n], b: [usize; n], c: [usize; n - 1]);

    let mut score = 0;
    let mut pre_b = a[0];
    for v in a {
        score += b[v - 1];
        if pre_b + 1 == v - 1 {
            score += c[pre_b];
        }
        pre_b = v - 1;
    }

    println!("{}", score);
}
//  [rust]
use proconio::{fastout, input, marker::Usize1};

#[fastout]
fn main() {
    input! {
        n:usize,
        a:[Usize1; n],
        b:[i64; n],
        c:[i64; n-1],
    }

    let mut res = 0;
    for i in 0..n {
        res += b[a[i]];
        if i > 0 {
            if a[i - 1] + 1 == a[i] {
                res += c[a[i - 1]];
            }
        }
    }

    println!("{}", res);
}
//  [rust]
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

    println!("{}", answer);
}

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let n: usize = iterator.next().unwrap().parse().unwrap();
    let a: Vec<usize> = (0..n).map(|_| iterator.next().unwrap().parse().unwrap()).collect();
    let b: Vec<usize> = (0..n).map(|_| iterator.next().unwrap().parse().unwrap()).collect();
    let c: Vec<usize> = (0..(n - 1)).map(|_| iterator.next().unwrap().parse().unwrap()).collect();

    let mut ans: usize = 0;
    for i in 0..n {
        ans += b[a[i] - 1];
        if i >= 1 && a[i - 1] + 1 == a[i] {
            ans += c[a[i - 1] - 1];
        }
    }
    return ans.to_string();
}
//  [swift]
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

let n:Int=Int(readLine()!)!
let a=readInts()
let b=readInts()
let c=readInts()
var ans=0

for i in 0..<n{ans+=b[i]}

for i in 0..<n-1{if a[i+1]-a[i]==1 {ans+=c[a[i]-1]}}


print(ans)
//  [typescript]
const main = lines => {
  console.log(solve(lines));
};

const solve = (lines: string[]): string => {
  const [N, A, B, C] = parseLines(lines);

  return A.reduce(
    (acc, cur) => {
      if (acc.prev + 1 === +cur) acc.sum += +C[+cur - 2];
      acc.prev = +cur;
      acc.sum += +B[+cur - 1];
      return acc;
    },
    { sum: 0, prev: -1 }
  ).sum.toString();
};

const parseLines = (lines: string[]) => {
  const obj = lines.map(e => e.split(' '));
  debug(obj);
  return obj;
};

const debug = (message?: any, ...optionalParams: any[]) => {
  if (!!process.env.LOCAL_DEBUG) console.log(message, ...optionalParams);
};

if (!process.env.LOCAL_DEBUG) {
  const { stdin: input, stdout: output } = process;
  input.resume();
  input.setEncoding('utf8');
  const lines = [];
  require('readline')
    .createInterface({ input, output })
    .on('line', line => lines.push(line))
    .on('close', () => main(lines));
}

export default solve;
//  [typescript]
import * as readline from 'readline';
const rl = readline.createInterface(process.stdin, process.stdout);

let line = 0;
let n: number;
let a: number[];
let b: number[];
let c: number[];

rl.on("line", input => {
  line++;
  if (line === 1) {
    n = parseInt(input);
  } else if (line === 2) {
    a = input.split(/\s+/).map(val=>parseInt(val));
  } else if (line === 3) {
    b = input.split(/\s+/).map(val=>parseInt(val));
  } else {
    c = input.split(/\s+/).map(val=>parseInt(val));

    let x = 0;
    for (let i = 0; i < n; i++) {
      x += b[a[i]-1];
      if (i > 0 && a[i] === (a[i-1] + 1)) {
        x += c[a[i-1]-1];
      }
    }
    console.log(x);
  }
});
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): any => {
  const N = +lines[0]
  lines.shift()
  const An = lines.map(line => line.split(` `).map(num => +num))
  const obj = { N, An }
  debug(obj)
  return obj
}

// solver
export const solve = (lines: string[]): string => {
  const { N, An } = parseLines(lines)
  let point = 0;
  let tmp = null;
  for(let i = 0; i < N; i++) {
    point += An[1][i]
    if (tmp !== null && An[0][tmp] + 1 === An[0][i]) {
      point += An[2][An[0][tmp] - 1]
    }
    tmp = i
  }
  return `${point}`

}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [python]
S=input()
if len(S)==1:
    print(0)
else:
    l=0
    r=0
    T=S[::-1]
    for i in range(1,len(S)):
        if S[i]==S[i-1]:
            if S[i]=='1':
                S=S[:i]+'0'+S[i+1:]
            else:
                S=S[:i]+'1'+S[i+1:]
            l+=1
    #print(l)
    #print(T)
    for i in range(1,len(T)):
        if T[i]==T[i-1]:
            if T[i]=='1':
                T=T[:i]+'0'+T[i+1:]
            else:
                T=T[:i]+'1'+T[i+1:]
            r+=1
    #print(r)
    print(min(l,r))
//  [python]
from numpy import zeros
s = list(map(int, list(input())))
ans1 = 0
ans2 = 0
sam1 = zeros(len(s))
sam2 = zeros(len(s))
for i in range(len(s)):
    if i%2: sam1[i] = 1
    else: sam2[i] = 1
for i in range(len(s)):
    if s[i] != sam1[i]: ans1 += 1
    elif s[i] != sam2[i]: ans2 += 1
print(min(ans1, ans2))
//  [python]
# -*- coding:utf-8 -*-

s = input()
s_list1 = list(s)
s_list2 = list(s)
count1 = 0
#count2 = 0

# 最初塗り替えない
s_len = len(s_list1)
pre = int(s_list1.pop(0))
for i in range(s_len-1):
    if pre == int(s_list1.pop(0)):
        pre = 1 - pre
        count1 += 1
    else:
        pre = 1 - pre
if count1 <= s_len//2:
    print(count1)
else:
    print(s_len-count1)
//  [java]
import java.util.Scanner;

public class Main {

	public static String Y = "Yes";
	public static String N = "No";
	public static long MOD = (long) (Math.pow(10, 9) + 7);
	public static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {

		String s = n();
		char[] sc = s.toCharArray();
		int n = s.length();

		String s1 = "";
		String s2 = "";

		int now1 = 0;
		int now2 = 1;

		for (int i = 0; i < n; i++) {
			s1 += now1 % 2;
			s2 += now2 % 2;
			now1++;
			now2++;
		}

		char[] sc1 = s1.toCharArray();
		char[] sc2 = s2.toCharArray();

		int count1 = 0;
		int count2 = 0;

		for (int i = 0; i < n; i++) {
			if (sc[i] != sc1[i]) {
				count1++;
			}
			if (sc[i] != sc2[i]) {
				count2++;
			}
		}
		out(min(count1, count2));

	}

	/*
	 * 以下メソッド集
	 */

	public static void permutation(String q, String ans) {
		// Base Case
		if (q.length() <= 1) {
			System.out.println(ans + q);
		}
		// General Case
		else {
			for (int i = 0; i < q.length(); i++) {
				permutation(q.substring(0, i) + q.substring(i + 1),
						ans + q.charAt(i));
			}
		}
	}

	static char[][] same(char[][] c, int h, int w) {

		char[][] a = new char[h][w];
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				a[i][j] = c[i][j];
			}
		}
		return a;

	}

	static int countkuro(char[][] c) {

		int count = 0;
		for (char[] cc : c) {
			for (char ccc : cc) {
				if ('#' == ccc) {
					count++;
				}
			}
		}
		return count;
	}

	static void debug() {

		out("---");
	}

	static void debug(Object a) {

		out("-------");
		out(a);
		out("-------");
	}

	static int ketasuu(int n) {

		String str = "" + n;
		return str.length();
	}

	static int account(String str) {

		String target = "AC";
		int count = 0;
		int len = str.length();
		for (int i = 0; i < len - 1; i++) {
			if (target.equals(str.substring(i, i + target.length()))) {
				count++;
			}
		}
		return count;
	}

	static int ni() {

		return sc.nextInt();
	}

	static long nl() {

		return sc.nextLong();
	}

	static double nd() {

		return sc.nextDouble();
	}

	static String n() {

		return sc.next();
	}

	static char[] nc() {

		return sc.next().toCharArray();
	}

	static int kaijo(int n) {

		if (n == 0 || n == 1) {
			return 1;
		} else {
			return n * kaijo(n - 1);
		}
	}

	static int fib(int n) {

		return (n == 1 || n == 0) ? n : fib(n - 2) + fib(n - 1);
	}

	static long lcm(long m, long n) {

		return m * n / gcd(m, n);
	}

	static int lcm(int m, int n) {

		return m * n / gcd(m, n);
	}

	static long gcd(long a, long b) {

		return (b == 0) ? a : gcd(b, a % b);
	}

	static int gcd(int a, int b) {

		return (b == 0) ? a : gcd(b, a % b);
	}

	static void out(Object obj) {
		System.out.println(obj);
	}

	static void outn(Object obj) {
		System.out.print(obj);
	}

	static double max(double d, double e) {

		return Math.max(d, e);
	}

	static long max(long a, long b) {

		return Math.max(a, b);
	}

	static long min(long d, long e) {

		return Math.min(d, e);
	}

	static int min(int a, int b) {

		return Math.min(a, b);
	}
}

class XY {

	int h;
	int c;

	XY(int h, int c) {
		this.h = h;
		this.c = c;
	}
}
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[]args) {
		try(Scanner scan = new Scanner(System.in)){
			
			String S = scan.next();
			int N = S.length();
			
			StringBuffer sb = new StringBuffer(S);
			StringBuffer sc = new StringBuffer(S);
			sc.reverse();
			//String SR =sc.toString();
			int count = 0;
			int countR = 0;
			
			if(N==1) {
				System.out.println(0);
			}else {
				
			
			for(int i = 1;i<N;i++) {
				String su = sb.substring(i-1, i);
				String sm = sb.substring(i, i+1);
				if(sm.equals(su)&&sm.equals("1")) {
					sb.replace(i, i+1, "0");
					count++;
					//System.out.println(sb);
				}else if(sm.equals(su)&&sm.equals("0")) {
					sb.replace(i, i+1, "1");
					count++;
					//System.out.println(sb);
				}
			}
			System.out.println();
				
			for(int i = 1;i<N;i++) {
				String su = sc.substring(i-1, i);
				String sm = sc.substring(i, i+1);
				if(sm.equals(su)&&sm.equals("1")) {
					sc.replace(i, i+1, "0");
					countR++;
					//System.out.println(sc);
				}else if(sm.equals(su)&&sm.equals("0")) {
					sc.replace(i, i+1, "1");
					countR++;
					//System.out.println(sc);
				}
			}
			
			System.out.println(count>countR?countR:count);
			
			
			}
			
			
		}
		
		
	}
		

}
//  [java]
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String pat = "";
    for (int i = 0; i < 50001; i++) {
      pat += "01";
    }

    String s = sc.next();
    int n01 = 0;
    int n10 = 0;

    for (int i = 0; i < s.length(); i++) {
      if (pat.charAt(i) != s.charAt(i)) {
        n01++;
      }
    }

    for (int i = 0; i < s.length(); i++) {
      if (pat.charAt(i + 1) != s.charAt(i)) {
        n10++;
      }
    }

    System.out.println(Math.min(n01, n10));

  }
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
int main() {
  char S[1000000] = {0};
  vector<int> s_v, s_01v, s_10v;
  cin >> S;
  //cout << strlen(S) << endl;
  for (int i = 0; i < strlen(S); i++) {
    s_v.push_back(S[i] - '0');
    switch(i%2) {
    case 0:
      s_01v.push_back(0);
      s_10v.push_back(1);
      break;
    case 1:
      s_01v.push_back(1);
      s_10v.push_back(0);
      break;
    }
  }
  long long int cnt_01 = 0, cnt_10 = 0;

  for (int i = 0; i < strlen(S); i++) {
    if (s_01v[i] != s_v[i]) cnt_01++;
    if (s_10v[i] != s_v[i]) cnt_10++;
  }
  if (cnt_01 > cnt_10) {
    cout << cnt_10 << endl;
  }
  else {
    cout << cnt_01 << endl;
  }
  // for (int i = 0; i < strlen(S); i++) {
  //   printf("%d ", s_v[i]);
  // }
  return 0;
}
//  [cpp]
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string.h>
#include<cmath>
#include<vector>
#include<queue>
 
using namespace std;
 
#define INF 2<<29
 
int main(){
char s[100005],s_0[100005],s_1[100005];
int ans0=0,ans1=0;
scanf("%s",s);
 
for(int i=0;i<strlen(s);i++){
s_0[i]='0'+(i%2);
s_1[i]='0'+((i+1)%2);
}
 
for(int i=0;i<strlen(s);i++){
if(s_0[i]!=s[i]) ans0++;
if(s_1[i]!=s[i]) ans1++;
}
 
printf("%d\n",min(ans0,ans1));
return 0;
}
//  [cpp]
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<queue>
#include<map>
#include<iomanip>
using namespace std;

int main(void){
 int ans1=0;
 int ans2=0;
 char S[200000];
 char S1[200000];

 cin>>S;
 strcpy(S1,S);
 
 if(S[0]=='1'){
  ans1++;
  S[0]='0';
 }
 for(int i=1; i<strlen(S); i++){
  if(S[i]!=S[i-1]);
  else{
   if(S[i]=='0')S[i]='1';
   else S[i]='0';
   ans1++;
  }
 }

 if(S1[0]=='0'){
  ans2++;
  S1[0]='1';
 }
 for(int i=1; i<strlen(S1);i++){
  if(S1[i]!=S1[i-1]);
  else{
   if(S1[i]=='0')S1[i]='1';
   else S1[i]='0';
   ans2++;
  }
 }

 cout<<min(ans1,ans2)<<endl;
 return 0;
}
//  [c]
#include<stdio.h>
int main(void)
{ char i[100000];
  scanf("%s",&i);
 int count=0;
 int j;
   for(j=1;j<strlen(i);j++)
   { if(i[j]==i[j-1] && i[j]=='1')
     { i[j]='0';count++;}
    if(i[j]==i[j-1] && i[j]=='0')
     { i[j]='1';count++;}
   }
 printf("%d",count);
 return 0;
}
//  [c]
#include<string.h>
#include<stdio.h>
int main(void){
    int i=0,cnt=0,x;
    char tile[100000];
    scanf("%s",tile);
    x=strlen(tile);
    do{
      if(tile[i]==tile[i+1]&&tile[i]=='1'){
      tile[i+1]='0';
      cnt++;
      
     
      }
     else if(tile[i]==tile[i+1]&&tile[i]=='0'){
      tile[i+1]='1';
      cnt++;
      
     
     }  
      i++;
    }while(i<strlen(tile));
  printf("%d",cnt);
   
    
  return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>

int main(void){
    char s[1000001];
    char ans[1000001];
    char start;
    int i;
    int cnt = 0;

    scanf("%s", s);
    //printf("入力された文字列は%s\n", s);
    start = s[0];

    //return 0;

    if(start == '0'){
        //printf("初めの文字は0\n");
        for(i = 0; i < strlen(s); i++){
            if(i % 2 == 0){ans[i] = '0';}
            else{ans[i] = '1';}
        }
    }else{
        //printf("初めの文字は1\n");
        for(i = 0; i < strlen(s); i++){
            if(i % 2 == 0){ans[i] = '1';}
            else{ans[i] = '0';}
        }
    }
    //これが必要なのか？？
    ans[strlen(s)] = '\0';

    //printf("あるべき文字列は%s\n", ans);

    //return 0;


    for(i = 0; i < strlen(s); i++){
        if(s[i] != ans[i]){cnt++;}
    }

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

    return 0;
}
//  [javascript]
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
 
var lines = [];
reader.on('line',(line) => {
          lines.push(line);
});
 
reader.on('close', () => {
          var line = lines[0];
  var s = [...line];
  var L = s.length
  var x = 0;
  for(var i = 0; i < L; i++){
    var D = i - s[i];
    if( D % 2 == 0){
      x = x + 1;
    }
  }
  if(x <= L/2){
    console.log(x);
  } else {
    console.log(L - x);
  }
});
//  [javascript]
function setUp(input) {
  input = input.split("\n");
  S = input[0];
  sList = S.split('');
  main();
}
function main() {
  var countOdd = 0;
  var countEven = 0;
  sList.forEach(function (d, i) {
    var target = i % 2;
    var oddTarget = target ? '0' : '1';
    var evenTarget = target ? '1' : '0';
    if (d != oddTarget) {
      countOdd++;
    }
    if (d != evenTarget) {
      countEven++;
    }
  })
  console.log(Math.min(countOdd, countEven));
}

setUp(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main
import "fmt"
func main() {
  var s,t0,t1 string
  var n,m0,m1 int
  fmt.Scan(&s)
  n = len(s)
  t0 = ""
  t1 = ""
  for i:=0;i<(n+1)/2;i++ {
    t0 += "01"
    t1 += "10"
  }
  m0 = 0
  m1 = 0
  for i:=0;i<n;i++ {
    if s[i:i+1] != t0[i:i+1] { m0++ }
    if s[i:i+1] != t1[i:i+1] { m1++ }
  }
  fmt.Println(min(m0,m1))
}
func min(n int,m int) int {
  if n < m { return n }
  return m
}
//  [go]
package main

import (
  "fmt"
  //"strconv"
)

func main() {
  var (
    nums string
    white string
  )

  fmt.Scan(&nums)
  //n := len(nums)
  for i:=range(nums) {
    if i%2==0{
      white += "0"
    } else {
      white += "1"
    }
  }

  dif_w:=0
  dif_b:=0
  for i:=range(nums) {
    if nums[i:i+1] != white[i:i+1] {
      dif_w += 1
    } else {
      dif_b += 1
    }
  }

  if dif_w > dif_b {
    fmt.Println(dif_b)
  } else {
    fmt.Println(dif_w)
  }

}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	// Code for C - Coloring Colorfully
	var S string
	fmt.Scanf("%s", &S)

	var A, B string
	for i := 0; i < len(S); i++ {
		if i%2 == 0 {
			A += string('0')
			B += string('1')
		} else {
			A += string('1')
			B += string('0')
		}
	}

	var countA, countB int
	for i := 0; i < len(S); i++ {
		if A[i] != S[i] {
			countB++
		} else {
			countA++
		}
	}

	fmt.Println(math.Min(float64(countA), float64(countB)))
}
//  [ruby]
#S = gets.to_i
cash = gets
S = cash.split("")
cash0 = ""
cash1 = ""
for i in 1...S.length do
  if i % 2 == 0 then
    cash0 = cash0 + "0"
    cash1 = cash1 + "1"
  else
    cash0 = cash0 + "1"
    cash1 = cash1 + "0"
  end
end

cash0 = cash0.split("")
cash1 = cash1.split("")

num0=0
num1=0
for i in 0...S.length do
  if S[i]==cash0[i] then
    num0=num0+1
  end
  if S[i]==cash1[i] then
    num1=num1+1
  end
end

if num0 > num1 then
  puts num1
else
  puts num0
end
//  [ruby]
s = gets.chomp.split("")


def switch_tile(n)
    n == 0 ? 1 : 0
end

def diff_cnt(left_array, right_array)
    raise RuntimeError.new("size not match #{left_array}:#{right_array}") unless left_array.size == right_array.size
    res = 0
    left_array.each_with_index do |i, idx|
        res += 1 if left_array[idx] != right_array[idx]
    end
    return res
end

def generate_tiles(l, first_zero = true)
    current = 1
    current = 0 if first_zero
    res = ""
    l.times do 
        res += current.to_s
        current = switch_tile(current)
    end
    return res
end

cand_a = generate_tiles(s.size, false).split("")
cand_b = generate_tiles(s.size, true).split("")

diff_a = diff_cnt(cand_a, s)
diff_b = diff_cnt(cand_b, s)

puts [diff_a, diff_b].min
//  [ruby]
n = gets
cnt = 0
n.length.times do |hoge|
    if hoge != 0 then 
        if n[hoge] == "0" and n[hoge - 1] == "0" then
           n[hoge] = "1"
           cnt += 1
        elsif n[hoge] == "1" and n[hoge - 1] == "1" then
            n[hoge] = "0"
            cnt += 1
        end
    end
end
puts cnt
//  [rust]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use itertools::Itertools;
use text_io::*;

const U_INF: usize = 1 << 60;
const I_INF: isize = 1 << 60;

fn main() {
    let s: String = read!();
    let n = s.len();
    let mut a = Vec::with_capacity(n);
    let mut b = Vec::with_capacity(n);

    for i in 0..n {
        if i%2==0 {
            a.push('1');
            b.push('0');
        }else{
            a.push('0');
            b.push('1');
        }
    }

    let s = s.chars().collect_vec();

    let mut ans_a = 0;
    let mut ans_b = 0;

    for i in 0..n {
        if a[i] != s[i] {
            ans_a += 1;
        }
        if b[i] != s[i] {
            ans_b += 1;
        }
    }
    
    println!("{}", ans_a.min(ans_b));
}
//  [rust]
#[allow(unused_imports)]
use std::{cmp::Reverse, collections::*};

#[allow(unused_imports)]
use proconio::{
    fastout, input,
    marker::{Chars, Usize1},
};

#[allow(unused_imports)]
use itertools::Itertools;

#[allow(unused_imports)]
use num::Integer;

#[fastout]
pub fn main() {
    input! {
        s: Chars,
    }

    println!(
        "{}",
        s.iter()
            .enumerate()
            .filter(|(i, &c)| if i % 2 == 0 { c == '0' } else { c == '1' })
            .count()
            .min(
                s.iter()
                    .enumerate()
                    .filter(|(i, &c)| if i % 2 == 1 { c == '0' } else { c == '1' })
                    .count()
            )
    );
}
//  [rust]
use proconio::input;

fn main() {
  input! {
    s: String,
  }
  let s = s.chars().collect::<Vec<char>>();
  
  let mut b_count = 0;
  let mut c_count = 0;
  
  for (i, c) in s.iter().enumerate() {
    let c = *c;
    if i % 2 == 0 && c == '0' {
      b_count += 1;
    } else if i % 2 == 1 && c == '1' {
      b_count += 1;
    }
  }
  
  for (i, c) in s.iter().enumerate() {
    let c = *c;
    if i % 2 == 0 && c == '1' {
      c_count += 1;
    } else if i % 2 == 1 && c == '0' {
      c_count += 1;
    }
  }
  
  if c_count < b_count {
    println!("{}", c_count);
  } else {
    println!("{}", b_count);
  }
}
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    func count() -> Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
}
extension Array where Element: Comparable {
    func max() -> Element! {
        return self.maxElement()
    }
    func min() -> Element! {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/



/*************** メインプログラム ***************/

let S = readLine()!.toArray()
var (tile1, tile2) = (0, 0)
for i in 0..<S.count {
    if i % 2 > 0 {
        if S[i] == "0" {
            tile1 += 1
        }
    } else {
        if S[i] == "1" {
            tile1 += 1
        }
    }
}
for i in 0..<S.count {
    if i % 2 > 0 {
        if S[i] == "1" {
            tile2 += 1
        }
    } else {
        if S[i] == "0" {
            tile2 += 1
        }
    }
}
print(min(tile1, tile2))
//  [swift]
let S=readLine()!.characters.map{String($0)}
var a=[0,0]
for i in 0..<2 {
    S.enumerate().forEach{j,c in if j%2^i != Int(c){a[i]++}}
}
print(min(a[0],a[1]))
//  [swift]
let S = readLine()!.characters.map{String($0)}
var a = S.count
for i in 0..<2 {
    var b = 0
    S.enumerate().forEach{j,c in if j%2^i != Int(c){b++}}
    a=min(a,b)
}
print(a)
//  [typescript]

const solve = (n) => {
  let a = {
    0: 0,
    1: 0
  }
  let b = {
    0: 0,
    1: 0
  }
  n.map((tile, i) => {
    if (i % 2 == 0) {
      a[tile]++
    } else {
      b[tile]++
    }
  })
  const p1 = a[0] + b[1]
  const p2 = a[1] + b[0]
  return Math.min(p1, p2)
  // ...
}
const main = (input) => {
  const n = input.split("")
  return solve(n)
}

if (process.env.NODE_ENV !== "test") {
  const input = require("fs").readFileSync("/dev/stdin", "utf8")
  console.log(main(input.trim()))
}
//  [typescript]
namespace Coder {
  class Scanner {
    private buffer: string = '';
    private stdinQueue: any = [];

    constructor() {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on(
        'data',
        (chunk): void => {
          this.buffer += chunk;
          while (this.stdinQueue.length > 0) {
            const i = this.buffer.indexOf('\n');
            if (i < 0) {
              break;
            }
            let line = this.buffer.substr(0, i);
            if (line.endsWith('\r')) {
              line = line.slice(0, -1);
            }
            this.buffer = this.buffer.substr(i + 1);
            this.stdinQueue.shift()(line);
          }
        },
      );
    }
    public getLine(): Promise<string> {
      return new Promise((resolve, reject) => {
        const i = this.buffer.indexOf('\n');
        if (i >= 0 && this.stdinQueue.length === 0) {
          let line = this.buffer.substr(0, i);
          if (line.endsWith('\r')) {
            line = line.slice(0, -1);
          }
          this.buffer = this.buffer.substr(i + 1);
          resolve(line);
        } else {
          this.stdinQueue.push(resolve);
        }
      });
    }

    public close(): void {
      process.stdin.pause();
    }
  }

  async function solve() {
    const sc = new Scanner();
    const S: string[] = (await sc.getLine()).split('');
    const odd: string[] = S.filter((v, i) => i % 2 === 1);
    const even: string[] = S.filter((v, i) => i % 2 === 0);

    const odd1 = odd.filter((x) => x === '1').length;
    const odd0 = odd.filter((x) => x === '0').length;
    const even1 = even.filter((x) => x === '1').length;
    const even0 = even.filter((x) => x === '0').length;

    let ans = 0;
    if (even0 === 0 && odd0 === 0) {
      ans = Math.min(even1, odd1);
    } else if (even1 === 0 && odd1 === 0) {
      ans = Math.min(even0, odd0);
    } else {
      ans = Math.min(odd0 + even1, even0 + odd1);
    }

    console.log(ans);
    sc.close();
  }

  solve();
}
//  [typescript]
let inp = require('fs').readFileSync('/dev/stdin', 'utf8').replace(/\n/g, '').trim();

const zoAry = Array.from(Array(Math.ceil(inp.length / 2))).map(_ => '01']).join('').split('');
const ozAry = Array.from(Array(Math.ceil(inp.length / 2))).map(_ => '10']).join('').split('');

let diffZo = 0;
let diffOz = 0;

inp.split('').forEach((v,i) => {
  if (v !== zoAry[i]) ++ diffZo;
  if (v !== ozAry[i]) ++ diffOz;
})

console.log(Math.min(diffZo, diffOz))
//  [python]
M = 2019
dp = [0] * M
s = input()
x = 0
for c in s:
    c = int(c)
    dp2 = [0] * M
    for j in range(M):
        index = (j*10 + c) % M
        dp2[index] += dp[j]
    dp = dp2
    dp[c] += 1
    x += dp[0]
print(x)
//  [python]
f=[0]*22209
def main():
    a=list(map(int,input()))
    n=len(a)
    ans=0
    d=[0]*2019
    d2=[0]*2019
    d2[a[0]]+=1
    for i in range(11):
        for j in range(2019):
            f[2019*i+j]=j
    for i in range(1,n):
        d[a[i]]+=1
        for j in range(2019):
            d[f[10*j+a[i]]]+=d2[j]
        ans+=d[0]
        for j in range(2019):
            d2[j]=d[j]
            d[j]=0
    print(ans)
main()
//  [python]
N = 2019
cnt = [0] * N
S = input()
ans = 0
for s in S:
    s = int(s)
    new = [0] * N
    for n in range(N):
        idx = (10 * n + s) % N
        new[idx] += cnt[n]
    cnt = new
    cnt[s] += 1
    ans += cnt[0]
print (ans)
//  [java]
import java.util.*;
import java.io.*;
public class Main{
  public static void main(String[] args) throws IOException{
    //Scanner sc = new Scanner(System.in);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s = br.readLine();
    char[] arr = s.toCharArray();
    int[] vec = new int[2019];
    int[] temp;
    vec[arr[0]-'0']=1;
    int count =0;
    //System.out.println("anuj"+vec[1]);
    for(int i=1;i<s.length();i++){
      temp = new int[2019];
      for(int j=0;j<2019;j++){
        if(vec[j]>0){
          //System.out.println("j "+j);
          int num = (j*10+arr[i]-'0')%2019;
          //System.out.println(num);
          temp[num]=vec[j];
        }
      }
      temp[arr[i]-'0']++;
      vec=temp;
      count+=vec[0];
    }
    System.out.println(count);
  }
}
//  [java]
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
	private static final int MOD = 2019;

	public static void main(String[] args) {
		var sc = new Scanner(System.in);
		var s = sc.next();
		var chars = s.toCharArray();
		var numbers = IntStream.range(0, chars.length).map(i -> Integer.valueOf(chars[i] - '0')).toArray();
		sc.close();

		var calc = new int[MOD][10];
		for (var i = 0; i < MOD; i++) {
			for (var j = 0; j < 10; j++) {
				calc[i][j] = (i * 10 + j) % MOD;
			}
		}

		var count = 0L;
		var init = new long[MOD];
		var set1 = new long[MOD];
		var set2 = new long[MOD];
		for (var i = 0; i < numbers.length; i++) {
			for (var j = 0; j < MOD; j++) {
				if (set1[j] > 0) {
					var number = calc[j][numbers[i]];
					if (number == 0) {
						count += set1[j];
					}
					set2[number] += set1[j];
				}
			}
			set2[numbers[i]]++;
			System.arraycopy(set2, 0, set1, 0, MOD);
			System.arraycopy(init, 0, set2, 0, MOD);
		}

		System.out.println(count);
	}
}
//  [cpp]
#include<bits/stdc++.h>
#include<limits>
#define ll long long
#define F first
#define S second
#define pb push_back
#define oo (1LL<<63-1)
#define endl '\n'
#define si size()
#define all(v) v.begin(),v.end()
#define FASTIO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define Matrix vector< vector < long long > >

using namespace std;

int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};

const long double Pi=acos(-1),e=2.718;
const int N=2e5+10,mod=1e9+7;
string s;
ll n,dp[2][2][2020];

int main ()
{
    FASTIO
    cin >> s;
    n=s.si;
    for(int i=n-1;i>=0;i--){
        for(int k=2018;k>=0;k--){
            for(int j=1;j>=0;j--){
                dp[i%2][j][k]=0;
                if(j==0){
                    dp[i%2][j][k] += dp[(i+1)%2][0][0];
                    dp[i%2][j][k] += dp[(i+1)%2][1][(k*10+s[i]-'0')%2019] + ((k*10+s[i]-'0')%2019==0);
                }
                if(j==1){
                    dp[i%2][j][k] += dp[(i+1)%2][1][(k*10+s[i]-'0')%2019] + ((k*10+s[i]-'0')%2019==0);
                }
            }
        }
    }
    cout << dp[0][0][0] << endl;
    return 0;
}
/**

*/
//  [cpp]
#include        <bits/stdc++.h>
using   namespace       std;
typedef long long ll;

// int/long:            -2,147,483,648 - 2,147,483,647 (-2^31 <= int < 2^31)
// long/long long:      -9,223,372,036,854,775,808 - 9,223,372,036,854,775,807 (-2^63 <= long < 2^63)

#define INF (1<<30)
//1,073,741,824
//= 536,870,912 *2

#define MOD 1000000007

#define Rep0(i, n)      for (auto i=0; i<n; i++)
#define Rep1(i, n)      for (auto i=1; i<=n; i++)
#define Sort(P) sort(P.begin(), P.end())
#define Rev(P)  reverse(P.begin(), P.end())

int     main() {
        int A=2019;
        string S;
        cin >>S;
        int N=S.size();
        vector<int> SS(N+1, 0);
        Rep1(i, N)
                SS.at(i)=S.at(i-1)-'0';
        vector<int> M(N+1, 0);
        vector<int> AA(N+1, 0);
        int ss=0;
        Rep1(i, N) {
                ss *=10;
                ss +=SS.at(i);
                ss %=A;
                M.at(i)=ss;
                int J=1;
                for (auto j=i-1; j>=0; j--) {
                        J*=10;
                        J%=A;
                        if (ss==((J*M.at(j))%A)) {
                                AA.at(i)=AA.at(j)+1;
                                break;
                        }
                }
        }
        int SSS=0;
        for (auto AAA: AA)
                SSS +=AAA;
        cout <<SSS <<endl;
        return 0;
}