jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))

s = 0
prev = -1

for i in range(N):
    t = A[i] - 1
    s += B[t]
    if prev != -1 and prev + 1 == t:
        s += C[prev]
    prev = t

print(s)
//  [python]
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
prev = -float('inf')
res = 0
for e in a:
    e -= 1
    res += b[e]
    if prev == e - 1:
        res += c[prev]
    prev = e
print(res)
//  [python]
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))

ans = 0
for i in range(N):
  a = A[i] - 1
  ans += B[a]
  if i > 0 and A[i] - A[i-1] == 1:
    ans += C[a-1]
print(ans)
//  [python]
kind = int(input())

table_1 = input().split(' ')
table_2 = input().split(' ')
table_3 = input().split(' ')
total = 0
for i in range(kind):
    total += int(table_2[i])

for j in range(kind-1):
    if int(table_1[j]) == int(table_1[j + 1]) - 1:
        total += int(table_3[j])
print(total)
//  [python]
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))

addans=0

for i in range(n-1) :
  if a[i]+1 == a[i+1] :
    addans += c[a[i]-1]
    print(addans)
print(sum(b)+addans)
//  [python]
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))

addans=0

for i in range(1,n) :
  if a[i-1]+1 == a[i] :
    addans += c[a[i-2]]
    print(addans)
print(sum(b)+addans)
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;

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

		FastScanner sc = new FastScanner();
		int n = sc.nextInt();

		int a[] = new int[n];
		int c[] = new int[n - 1];

		for (int j = 0; j < n; j++) {
			a[j] = sc.nextInt();
		}

		int result = 0;
		for (int j = 0; j < n; j++) {
			result += sc.nextInt();
		}

		for (int j = 0; j < n - 1; j++) {
			c[j] = sc.nextInt();
		}


		for (int i = 0; i < n - 1; i++) {
			result += (a[i] + 1 == a[i + 1] ? c[a[i] - 1] : 0);
		}

		System.out.println(result);
	}
}

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.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax 
    static final int INF = 1_000_000_000; // 10^9  
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		int n = saori.saori_hayami();
		int[] a = new int[n];
		int[] b = new int[n];
		int[] c = new int[n-1];
		for(int i = 0;i < n;i++){
			a[i] = saori.saori_hayami();
		}
		for(int i = 0;i < n;i++){
			b[i] = saori.saori_hayami();
		}
		for(int i = 0;i < n-1;i++){
			c[i] = saori.saori_hayami();
		}
		int ans = 0;
		ans = b[a[0]-1];
		for(int i = 1;i < a.length;i++){
			ans += b[a[i]-1];
			if(a[i] - a[i-1] == 1){
				ans += c[a[i-1]-1];
			}
		}
		System.out.println(ans);
		saori.close();
    }
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() { 
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) { 
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() { 
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }
    
}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {

        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(is);

        List<String> mylist = new ArrayList<>();

        // 標準入力からの値を変数strinputに代入
        String strinput = reader.readLine();

        while (strinput != null) {

            mylist.add(strinput);
            strinput = reader.readLine();

        }
        String arr01[] = mylist.get(0).split(" ");
        String arr02[] = mylist.get(1).split(" ");
        String arr03[] = mylist.get(2).split(" ");
        String arr04[] = mylist.get(3).split(" ");

        String s = arr01[0];
        Integer n = Integer.valueOf(s);

        int mysum = 0;
        for (String v : arr03) {
            mysum += Integer.valueOf(v);

        }

        for (int i = 0; i < n - 1; i++) {

            int temp = Integer.valueOf(arr02[i]);

            if (temp + 1 == Integer.valueOf(arr02[i + 1])) {
                mysum += Integer.valueOf(arr04[temp - 1]);
            }

        }

        System.out.println(mysum);
    }

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

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int[] A = new int[N + 1];
		int[] B = new int[N + 1];
		int[] C = new int[N];
		int sum = 0;
		int target = -1;
		int add = 0;

		for (int i = 1; i < N + 1; i++) {
			A[i] = sc.nextInt();
		}
		for (int i = 1; i < N + 1; i++) {
			B[i] = sc.nextInt();
		}
		for (int i = 1; i < N; i++) {
			C[i] = sc.nextInt();
		}

		for (int i = 1; i < N + 1; i++) {
			sum+=B[A[i]];
			//addできるか
			if (A[i] == target) {
				sum+=add;
				target = -1;
			}

			//C確認
			if (A[i] < C.length) {
				target = A[i] + 1;
				add = C[A[i]];
			}

		}

		System.out.println(sum);
	}

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

public class Main {

	public static void main(String[] args) {
		// TODO 140_B
		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();

		int[] A = new int[N];
		int[] B = new int[N];
		int[] C = new int[N];

		int i = 0;
		int ret = 0;

		for(i=0; i<N; i++) {
			A[i] = sc.nextInt();
		}
		for(i=0; i<N; i++) {
			B[i] = sc.nextInt();
		}
		for(i=0; i<N-1; i++) {
			C[i] = sc.nextInt();
		}
	    // Scannerクラスのインスタンスをクローズ
		sc.close();

		for(i=0; i<N; i++) {
			ret += B[i];
			ret += C[i];
		}

		// 最後に食べた料理だけ、追加の満足度はゼロ（差し引き）
		ret -= C[A[N-1]-1];

		System.out.println(ret);

	}

}
//  [java]

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ

		try(Scanner sc = new Scanner(System.in)){
			int n = sc.nextInt();
			int[] a = new int[n];
			int[] b = new int[n];
			int[] c = new int[n-1];

			//Input

			for(int i = 0; i < n; i++) {
				a[i] = sc.nextInt();
			}
			for(int i = 0; i < n; i++) {
				b[i] = sc.nextInt();
			}
			for(int i = 0; i < n - 1; i++) {
				c[i] = sc.nextInt();
			}

			//けーさん
			int ans = 0;
			for(int i = 0; i < n; i++) {
				ans +=b[a[i] - 1];
				if(i != n - 1 && a[i] + 1 == a[i + 1]) {
					ans += c[i - 1];
				}

			}
			System.out.println(ans);
		}
	}

}
//  [cpp]
#include <cstdio>
#include <unordered_map>
typedef long long ll;
#define re register

#define gc getchar
#define pc putchar
#define sp pc(' ')
#define ln pc('\n')

template <class t>
inline void read(t&num) {
    register char c = gc();
    register bool flag = 0;
    while (c != '-' && (c < '0' || c > '9')) c = gc();
    if (c == '-') flag = 1, c = gc();
    num = 0;
    while (c >= '0' && c <= '9') num = (num << 1) + (num << 3) + (c ^ 48), c = gc();
    flag && (num = ~(num - 1));
}

template <class t>
inline void print(t num) {
    if (num < 0) pc('-'), num = ~(num - 1);
    if (num >= 10) print(num / 10);
    pc(num % 10 ^ 48);
}

int n;
int a[21], b[21], c[21];

int main() {
    read(n);
    for (int i = 1; i <= n; i++) read(a[i]);
    for (int i = 1; i <= n; i++) read(b[i]);
    for (int i = 1; i < n; i++) read(c[i]);
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        ans += b[a[i]];
        if (a[i + 1] == a[i] + 1) ans += c[a[i]];
    }
    print(ans), ln;
}
//  [cpp]
#include<bits/stdc++.h>
#include<string>
#include<map>
#define ll          long long
#define pb          push_back
#define mp          make_pair
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define vii         vector<pair<ll,ll> >
#define vi          vector<int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (int)x.size()
#define hell        1000000007
#define endl        '\n'
#define rep(i,a,b)  for(ll i=a;i<b;i++)
#define rep1(i,a,b) for(ll i=a;i<= b;i++)
#define PI          3.14159
#define MAX         100000001
#define fast_io      ios_base::sync_with_stdio(false);  cin.tie(0); cout.tie(0);
#define scan(var)    scanf("%lld",&var)
#define print(var)   printf("%lld\n", var);
#define BLOCK 317
#define double       long double
#define mod          998244353
using namespace std;
ll arr[21];
ll arr1[21];
ll arr2[21];
int main()
{
  fast_io
  ll n;
  cin >> n;
  rep(i,1,n + 1)
  {
    cin >> arr[i];
  }
  rep(i,1,n + 1)
  {
    cin >> arr1[i];
  }
  rep(i,1,n)
  {
    cin >> arr2[i];
  }
  ll prev = -1;
  ll ans = 0;
  rep(i,1,n + 1)
  {
    ans += arr1[arr[i]];
    if(prev != -1)
    {
      if(prev == arr[i] - 1)
      {
        ans += arr2[prev];
      }
    }
    prev = arr[i];
  }
  cout << ans;
  return 0;
}
//  [cpp]
#pragma GCC optimize("-O3")

#include <bits/stdc++.h>

using namespace std;

#define ll long long

signed main() {
	int n; cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; ++i)
		cin >> a[i];
	ll ans = 0;
	for (int i = 0; i < n; ++i) {
		int b; cin >> b;
		ans += b;
	}
	vector<int> c(n - 1);
	for (int i = 0; i < n - 1; ++i)
		cin >> c[i];
	for (int i = 0; i < n - 1; ++i) {
		if (a[i] + 1 == a[i + 1])
			ans += c[a[i] - 1];
	}

	cout << ans << endl;
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (ll i = 0; i < (ll)n; i++)
#define Rep(i, s, n) for (ll i = (ll)s; i < (ll)n; i++)
typedef long long ll;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    int n;
    cin >> n;
    int a[n], b[n], c[n-1];
    rep (i, n) cin >> a[i];
    rep (i, n) cin >> b[i];
    rep (i, n-1) cin >> c[i];
    int res = 0;
    rep (i, n) {
        res += b[a[i]-1];
        if (i > 0) {
            if (a[i]-a[i-1] == 1) res += c[a[i]-2];
        }
    }
    cout << &c[0] << endl;
}
//  [cpp]
#pragma region header
#define _GLIBCXX_DEBUG 
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>
using namespace std;
#define int long long
using ll = long long;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
constexpr ll mod = 1e9 + 7;
constexpr ll inf = INT32_MAX / 2;
constexpr ll INF = LLONG_MAX / 2;
constexpr long double eps = DBL_EPSILON;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */
/* --------------------テンプレート------------------ */
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;
}
/* ----------------------end----------------------- */

/* --------------------ライブラリ-------------------- */
ll fact(int i) {       //階乗
    if (i == 0) return 1;
    return (fact(i - 1)) * i % mod;
}
ll gcd(ll a, ll b) {        //最大公約数
    if (b == 0) return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) {      //最小公倍数
    return a * b / gcd(a, b);
}
bool isprime(ll a)//素数判定、primeならtrue,違うならfalse
{
    if (a < 2) return false;
    else if (a == 2) return true;
    else if (a % 2 == 0) return false;
    double m = sqrt(a);
    for (int i = 3; i <= m; i += 2)
    {
        if (a % i == 0)
        {
            return false;
        }
    }
    // 素数である
    return true;
}
ll keta(ll n) {        //桁数を求める
    if (n == 0) return 1;
    int count = 0;
    while (n != 0) {
        n /= 10;
        count++;
    }
    return count;
}
ll ketasum(ll n) {    //各桁の和
    ll sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
/* ----------------------end----------------------- */
#pragma endregion
signed main() {
    int N;
    cin>>N;
    int ans=0;

    vector<int>A(N);
    vector<int>B(N);
    vector<int>C(N-1);
    for(int i=0;i<N;i++){
        cin>>A[i];
    }
    for(int i=0;i<N;i++){
        cin>>B[i];
    }
    for(int i=0;i<N-1;i++){
        cin>>C[i];
    }
    for(int i=0;i<N;i++){
        if(A[i+1]-1==A[i]){
            ans+=(B[i]+C[i]);
        }
        else{
            ans+=B[i];
        }
    }
    cout<<ans<<endl;
}
//  [cpp]
#include <iostream>
#include <vector>

int main() {
  int n;
  std::cin >> n;
  std::vector<int> a(n), b(n), c(n);
  for (int i = 0; i < n; ++i) {
    std::cin >> a[i];
    a[i]--;
  }
  for (int i = 0; i < n; ++i)
    std::cin >> b[i];
  for (int i = 0; i < n - 1; ++i)
    std::cin >> c[i];

  int sum = 0;
  for (int i = 0; i < n; ++i)
    sum += b[a[i]];

  for (int i = 0; i < n - 1; ++i)
    if (a[i] + 1 == a[i + 1])
      sum += c[i];

  std::cout << sum << std::endl;
}
//  [c]
int main(void){
  int n,a[20],b[20],c[20];
  
  scanf("%d",&n);
  
  int i,sum=0;
  
  for(i=0; i<n; i++){
    scanf("%d",&a[i]);
  }
  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-1; i++){
    sum += b[a[i]-1];
    if(a[i+1]-a[i] == 1)
      sum += c[a[i]-1];
  }
  
  sum += b[a[n-1]-1];
  
  printf("%d",sum);
}
//  [c]
#include<stdio.h>
int main(){
  int n,i,count=0,score;
  scanf("%d",&n);
  int a[n+1],c[n+1];
  for(i=0;i<n;i++)
    scanf("%d",&a[i]);
  for(i=0;i<n;i++){
    scanf("%d",&score);
    count+=score;
  }
  for(i=0;i<n-1;i++)
    scanf("%d",&c[i]);
  for(i=0;i<n-1;i++){
    if(a[i]==a[i+1]-1)
      count+=c[a[i]-1];
  }
  printf("%d\n",count);
  return 0;
}
//  [c]
#include "stdio.h"



int main(void) {

	int number;
	int array[20], barray[20], carray[19];
	int sum = 0;
	scanf("%d", &number);

	for (int i = 1; i<=number; i++) {
		scanf("%d", &array[i]);
	}
	for (int i = 1; i<=number; i++) {
		scanf("%d", &barray[i]);
	}
	for (int i = 1; i<=number - 1; i++) {
		scanf("%d", &carray[i]);
	}

	for (int i = 1; i<=number; i++) {
		sum += barray[array[i]];
			if ((array[i] == array[i-1] + 1) && (i != 1)) {
				sum += carray[array[i-1]];
			}
	}
	printf("%d\n", 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((a[i] - a[i-1] == 1)) {
      ans += c[a[i]];
    }
  }

  printf("%d\n", ans);
  
  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((a[i] - a[i-1] == 1)) {
      ans += c[a[i-1]];
    }
  }

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

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

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

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

  ans += b[a[0]-1];

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

  printf("%d", ans);

  return 0;
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	var N = Number(input[0])
	//文字列から10進数に変換するときはparseIntを使います
    var a = input[1].split(" ") 
	var b = input[2].split(" ") 
    var c = input[3].split(" ") 
    
    var answer = 0
    
    for(var i =0; i<N ;i++){
      
      var aa = Number(a[i])
      var zz = Number(b[aa - 1])
      
      answer = answer + zz
     
      if(i != 0 && aa == Number(a[i - 1]) + 1){
        var cc = Number(c[aa - 2])
        answer = answer + cc
      }    
     }
    
	//出力
	console.log(answer);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
	input = input.trim();
	input = input.split("\n");

	var shurui = input[0];
	var ryori = input[1].split(" ");
	var manzoku = input[2].split(" ");
	var manzoku_plus = input[3].split(" ");

	var manzoku_sum = 0;
	var ryori_order = 0;
	var ryori_order_back = 0;
	for (var i = 0; i < ryori.length; i++) {

		ryori_order = Number(ryori[i]);
		manzoku_sum += Number(manzoku[ryori_order - 1]);

		if (i > 0 && ryori_order_back + 1 == ryori_order) {
			manzoku_sum += Number(manzoku_plus[ryori_order_back - 1]);
		}
		ryori_order_back = ryori_order;
		
	}

	console.log(manzoku_sum);
	
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
const Main = (input)=>{
	let xs = input.trim().split("\n");
    let N = xs[0].split(" ").map(Number);
    let A = xs[1].split(" ").map(Number);
    let B = xs[2].split(" ").map(Number);
    let C = xs[3].split(" ").map(Number);
    let ans = 0;  
      for(let i = 0; i < N; i++){
        ans += B[A[i]-1];
          if(i >= 1){
          let a = A[i];
          let b = A[i-1];
            if(a-b == 1){
            ans += C[A[i]-2];
            }
          }
        }
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let a = nextIntArray()
    let b = nextIntArray()
    let c = nextIntArray()
    let ans = 
    for(let i = 0;i<a.length; i++){
        ans += b[a[i]-1]
        if(a[i]+1 == a[i+1]) ans += c[a[i]-1]
    }
    console.log(ans)
}
Main()
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let a = nextIntArray()
    let b = nextIntArray()
    let c = nextIntArray()
    let ans = b[a[0]]
    for(let i = 1;i<a.length; i++){
        ans += b[a[i]-1]
        if(a[i]+1 == a[i+1]) ans += c[a[i]-1]
    }
    console.log(ans)
}
Main()
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let a = nextIntArray()
    let b = nextIntArray()
    let c = nextIntArray()
    let ans = b[a[0]]
    for(let i = 1;i<a.length; i++){
        ans += b[a[i]]
        if(a[i]-1 == i-1) ans += c[a[i]]
    }
    console.log(ans)
}
Main()
//  [go]
package main

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

const (
	defaultBufferSize = 1024
	maxBufferSize     = 1e6
	Mod               = 1e9 + 7
)

var sc = bufio.NewScanner(os.Stdin)

// sc.Buffer(make([]byte, defaultBufferSize), maxBufferSize)

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

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

func readInt64() int64 {
	sc.Scan()
	i, err := strconv.ParseInt(sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return int64(i)
}

func readfloat64() float64 {
	sc.Scan()
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}

func abs(a int) int {
	if a < 0 {
		return a * -1
	}
	return a
}

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

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

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func ModComb(n, k int) int {
	if k == 0 {
		return 1
	}
	x, y := n, k
	for i := 1; i < k; i++ {
		x = x * (n - i) % Mod
		y = y * (k - i) % Mod
	}
	inv := ModInv(y)
	return x * inv % Mod
}

func ModFact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % Mod
	}
	return fact
}

func ModInv(x int) int {
	return ModPow(x, Mod-2)
}

func ModPow(a, n int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % Mod
		}
		a = a * a % Mod
		n /= 2
	}
	return res
}

func pow(a, n int) int {
	if n == 0 {
		return 1
	}

	ans := 0
	if n%2 == 0 {
		ans = pow(a*a, n/2)
	} else {
		ans = a * pow(a*a, (n-1)/2)
	}
	return ans
}

func intSliceReverse(slice []int) []int {
	for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
		slice[i], slice[j] = slice[j], slice[i]
	}
	return slice
}

func stringReverse(str string) string {
	runes := []rune(str)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func primeFactorization(x int) map[int]int {
	result := make(map[int]int, 0)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			result[i]++
			x /= i
		}
	}
	if x != 1 {
		result[x]++
	}
	return result
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	for i := 2; i*i <= x; i++ {
		if i == x {
			continue
		}
		if x%i == 0 {
			return false
		}
	}
	return true
}

func main() {
	sc.Split(bufio.ScanWords)
	n := readInt()
	A := make([]int, n)
	B := make([]int, n)
	C := make([]int, n-1)

	for i := 0; i < n; i++ {
		A[i] = readInt()
	}
	for i := 0; i < n; i++ {
		B[i] = readInt()
	}
	for i := 0; i < n-1; i++ {
		C[i] = readInt()
	}

	ans := 0
	prev := 0
	for i := 0; i < n; i++ {
		ans += B[A[i]-1]
		if i > 0 && A[i]-1-prev == 1 {
			ans += C[prev]
		}
		prev = A[i] - 1
	}
	fmt.Println(ans)
}
//  [go]
package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

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

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

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

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	N := getInt()
	a := make([]int, N)
	b := make([]int, N)
	c := make([]int, N-1)
	for i := 0; i < N; i++ {
		a[i] = getInt() - 1
	}
	for i := 0; i < N; i++ {
		b[i] = getInt()
	}
	for i := 0; i < N-1; i++ {
		c[i] = getInt()
	}

	prev := -1
	ans := 0
	for i := 0; i < N; i++ {
		x := a[i]
		ans += b[x]
		if x == prev+1 && x != 0 {
			ans += c[x-1]
		}
		prev = x
	}
	out(ans)
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)

	n := nextInt()
	alist := make([]int, n)
	blist := make([]int, n)
	clist := make([]int, n)
	bsum := 0
	for i := 0; i < n; i++ {
		alist[i] = nextInt()
	}
	for i := 0; i < n; i++ {
		blist[i] = nextInt()
		bsum += blist[i]
	}
	for i := 0; i < n-1; i++ {
		clist[i] = nextInt()
	}
	for i := 1; i < n; i++ {
		if alist[i]-alist[i-1] == 1 {
			bsum += clist[alist[i-1]-1]
		}
	}

	fmt.Println(bsum, clist)
}

// ---- readfunc
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

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

var (
	read  = bufio.NewReader(os.Stdin)
	write = bufio.NewWriter(os.Stdout)
)

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

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

func yesno(result bool) {
	if result {
		fmt.Fprintln(write, "Yes")
	} else {
		fmt.Fprintln(write, "No")
	}
}

func printansStr(result bool, a, b string) {
	if result {
		fmt.Fprintln(write, a)
	} else {
		fmt.Fprintln(write, b)
	}
}

func printansInt(result bool, a, b int) {
	if result {
		fmt.Fprintln(write, a)
	} else {
		fmt.Fprintln(write, b)
	}
}

func main() {
	defer write.Flush()

	var n int
	fmt.Fscan(read, &n)

	A := make([]int, n)
	B := make([]int, n)
	C := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(read, &A[i])
	}
	for i := 0; i < n; i++ {
		fmt.Fscan(read, &B[i])
	}
	for i := 0; i < n-1; i++ {
		fmt.Fscan(read, &C[i])
	}

	pre := -1
	sum := 0
	for i := 0; i < n; i++ {
		sum += B[A[i]-1]
		if pre+1 == A[i]-1 {
			sum += C[pre]
		}
		pre = A[i] - 1
	}
	fmt.Println(sum)

}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

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

	ali := make([]int, n, n)

	sc.Split(bufio.ScanWords)

	for i := 0; i < n; i++ {
		ali[i] = nextInt()
	}

	bli := make([]int, n, n)

	for i := 0; i < n; i++ {
		bli[i] = nextInt()
	}

	cli := make([]int, n-1, n-1)

	for i := 0; i < n-1; i++ {
		cli[i] = nextInt()
	}

	count := sum(bli)

	tmpA := ali[0]
	for i := 0; i < n; i++ {
		if ali[i] == tmpA+1 {
			if i == 1 {
				count += cli[len(cli)-1]
			} else if i == n-1 {
				count += cli[0]
			} else {
				count += cli[i-1]
			}
		}
		tmpA = ali[i]
	}

	fmt.Println(count)
}

func sum(a []int) int {
	s := 0
	for i := 0; i < len(a); i++ {
		s += a[i]
	}
	return s
}

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
//  [ruby]
lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]

ans = 0
last_dish = -10
for i in 1..N do
  dish = lines[1][i-1]
  ans += lines[2][dish-1]
  if dish == last_dish + 1 then
    ans += lines[3][last_dish-1]
  end
  last_dish = dish
end
print ans
//  [ruby]
N = gets.to_i
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
C = gets.split.map(&:to_i)
before = -1
res = 0
A.each do |a|
    res += B[a-1]
    if before == a-1 then
        res += C[before-1]
    end
    before = a
end
puts res
//  [ruby]
n = gets.to_i
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)

ans = 0
a.each.with_index do |n, i|
  ans += b[n-1]
  if i > 0 && a[i] - a[i-1] == 1
    ans += c[a[i]-2]
  end
end
p ans
//  [ruby]
n,a,b,c=$<.map{_1.split.map &:to_i}
p b.sum+(0..n-2).sum{|i|a[i]+1==a[i+1] ? c[a[i]-1] : 0}
//  [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)
sum = 0
n.times do |i|
  sum += b[a[i] - 1]
  if a[i-1] + 1 == a[i]
    sum += c[a[i-1]-1]
  end
end

puts sum
//  [ruby]
num = gets
desh = gets.chomp.split(' ')
manzoku1 = gets.chomp.split(' ')
manzoku2 = gets.chomp.split(' ')

for i in 0..num do
  if i > 0 
  	result += manzoku2[i-1] if desh[i-1] == (desh[i]+1)
  result += manzoku1[i]
end
puts result
//  [rust]
use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let n = match buf.trim().parse::<i32>() {
		Ok(m) => m,
		_ => panic!(""),
	};
	
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut a = Vec::new();
	for j in iter {
		let i = match j.parse::<i32>() {
			Ok(m) => m,
			_ => panic!(""),
		};
		a.push(i);
	}
	
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut b = Vec::new();
	for j in iter {
		let i = match j.parse::<i32>() {
			Ok(m) => m,
			_ => panic!(""),
		};
		b.push(i);
	}
	
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut c = Vec::new();
	for j in iter {
		let i = match j.parse::<i32>() {
			Ok(m) => m,
			_ => panic!(""),
		};
		c.push(i);
	}
	let mut ret = 0;
	for i in 0..n {
		let num = a[i as usize];
		ret = ret + b[(num - 1) as usize];
		if i+1 < n && a[(i+1) as usize] == num + 1 {
			ret = ret + c[(num - 1) as usize];
		}
	}
	println!("{}", ret);
}
//  [rust]
/* {{{ */
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
/* }}} */

fn main() {
    input! {
        n: usize,
        a: [usize1;n],
        b: [u32;n],
        c: [u32;n-1]
    }
    let mut res = b[a[0]];
    for i in 1..n {
        res += b[a[i]];
        if a[i-1] + 1 == a[i] {
            res += c[a[i]-1];
        }
    }
    println!("{}", res);
}
/* vim:set foldmethod=marker: */
//  [rust]
fn input1<T: std::str::FromStr> () -> Result<T, T::Err> {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).unwrap();
    n.trim().parse()
}

fn input_arr<T: std::str::FromStr> () -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().flat_map(str::parse).collect()
}

fn main() {
    let n: usize = input1().unwrap();
    let a: Vec<usize> = input_arr();
    let b: Vec<usize> = input_arr();
    let c: Vec<usize> = input_arr();

    let mut prev = n;
    let mut result = 0;
    for av in a.into_iter() {
        let i = av - 1;
        result += b[i];
        if i == 1 + prev {
            result += c[prev];
        }
        prev = i;
    }
    println!("{}", result);
}
//  [rust]
#![allow(unused_imports)]

//input
use proconio::input;
use proconio::marker::{Bytes, Chars};
//use std::io::Read;

//collections
//use std::collections::BTreeMap;
//use std::collections::BTreeSet;
//use std::collections::HashMap;
//use std::collections::HashSet;
//use std::collections::VecDeque;
//use std::collections::BinaryHeap;

//use std::cmp::*;

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

    let mut ans = b[a[0] - 1];
    let mut bf = a[0];

    for i in 1..n {
        ans += b[a[i] - 1];
        if a[i] != 1 {
            if bf + 1 == a[i] {
                ans += c[bf - 1];
            }
        }
        bf = a[i];
    }

    println!("{}", ans);
}
//  [rust]
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 main() {
	let n: u32 = read();
	let mut a: Vec<u32> = Vec::new();
	let mut b: Vec<u32> = Vec::new();
	let mut c: Vec<u32> = Vec::new();
	for i in 0..n{
		a.push(read());
	}
	for i in 0..n{
		b.push(read());
	}
	for i in 0..n-1{
		c.push(read());
	}

	let mut result = 0;
	let mut past_ai = 0;
	
	for ai in a {
		result += b[(ai-1) as usize];
		if (ai > past_ai && ai-past_ai == 1) || (ai <= past_ai && past_ai-ai == 1) {
			result += c[(past_ai-1) as usize];
		}
		past_ai = ai;
	}
	println!("{}", result);

}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}


fn main() {
    input! {
        n: i32,
        a: [i32; n],
        b: [i32; n],
        c: [i32; n-1]
    }
    let mut ans: i32 = 0;
    let mut bef: i32 = 1000;
    for i in 0..n {
        ans += b.get(a.get(a).unwrap()).unwrap();
        if bef + 1 == a.get(a).unwrap() {
            ans += c.get(bef).unwrap();
        }
        bef = a.get(a).unwrap();
    }
    println!("{}", ans);
}
//  [swift]
var i:[Int]{return readLine()!.characters.split(" ").map{Int(String($0))!}}
let N=i[0],A=i.map{$0-1},B=i,C=i
print((0..<N).reduce(0){$0+B[A[$1]]+(0<$1&&A[$1-1]+1==A[$1] ?C[A[$1-1]]:0)})
//  [swift]
let n = Int(readLine()!)!

let a = readLine()!.characters.split{$0 == " "}.map{ Int(String($0))! }
let b = readLine()!.characters.split{$0 == " "}.map{ Int(String($0))! }
let c = readLine()!.characters.split{$0 == " "}.map{ Int(String($0))! }

var ret = 0

for i in 0..<a.count {
  ret += b[a[i] - 1]
  if (i != 0) && (a[i] == a[i - 1] + 1) {
    ret += c[a[i - 1] - 1]
  }
}

print(ret)
//  [swift]
import Foundation
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
let n=Int(readLine()!)!
var aa=readInts()
var bb=readInts()
var cc=readInts()
var before=0
var ans=0
for a in aa{
  ans+=bb[a-1]
  if before==a-1{
    ans+=cc[a-2]
  }
  before=a
}
print(ans)
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const input = stdin.split('\n')

const n = Number(input[0])
const a = input[1].split(' ').map(Number)
const b = input[2].split(' ').map(Number)
const c = input[3].split(' ').map(Number)

const ans = () => {
  let prevFood = -100
  let count = 0
  for (let i = 0; i < n; i++) {
    const food = a[i] - 1

    const m = b[food]

    const additionalM = food === prevFood + 1 ? c[food - 1] : 0

    count += m + additionalM

    prevFood = food
  }

  console.log(count)
}

ans()
//  [typescript]
function solve() {
    const input = (require('fs').readFileSync("/dev/stdin", "utf8") as string).split("\n");
    const N = +input[0];
    const A = input[1].split(" ").map((x: string): number => +x);
    const B = input[2].split(" ").map((x: string): number => +x);
    const C = input[3].split(" ").map((x: string): number => +x);

    let ans = 0;
    let prev = -1;
    for (let i = 0; i < N; i++) {
        ans += B[A[i] - 1];
        if (prev + 1 == A[i]) {
            ans += C[A[i] - 1 - 1];
        }
        prev = A[i];
    }
    console.log(ans);
}

solve();
//  [typescript]
import * as fs from "fs"
const NUMBER_MIN = Math.ceil(Number.MIN_SAFE_INTEGER / 2)

const process = (n: number, a: number[], b: number[], c: number[]): string => {
  let lastEat = NUMBER_MIN
  let res = 0

  for (let i = 0; i < n; i++) {
    const ryouri = a[i]
    const manzoku = b[ryouri - 1]
    res += manzoku
    if (lastEat + 1 === ryouri - 1) {
      res += c[ryouri - 2]
    }
    lastEat = ryouri - 1
  }

  return "" + res
}

const Main = (input: string): string => {
  const aa: string[][] = input.split("\n").map((e) => e.split(" "))
  const na0: number[] = aa[0].map((e) => parseInt(e))
  const [n] = na0

  const res =
    process(
      n,
      aa[1].map((e) => parseInt(e)),
      aa[2].map((e) => parseInt(e)),
      aa[3].map((e) => parseInt(e))
    ) + ""
  console.log(res)
  return res
}
Main(fs.readFileSync("/dev/stdin", "utf8"))
//  [typescript]
function main(input) {
    const lines = input.split('\n');
    const names = lines[1].split(' ').map(item => +item)
    const manzoku = lines[2].split(' ').map(item => +item)
    const manzoku_a = lines[3].split(' ').map(item => +item)

    let res = 0
    for (let i = 0; i < names.length; i++) {
        if (i > 0) {
            if (names[i] - 1 === names[i - 1]) {
                res += manzoku_a[i]
            }
        }

        res += manzoku[i]
    }
    console.log(res)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
import { readFileSync } from 'fs'
function main() {
  const input = readFileSync('/dev/stdin', 'utf8')
  const [n, a, b, c] = input.trim().split('\n').map(v => v.trim().split(' ').map(string => parseInt(string))) 
  console.log(n, a, b, c)
  let result = 0  
  for (let i = 0; i < a.length; i++) {
    const number = a[i] - 1
    result += b[number]
    if (number !== a.length && i + 1 !== a.length && a[i] + 1 === a[i + 1]) {
      result += c[number]
    }
  }
  console.log(result)
}
main()
//  [typescript]
import { readFileSync } from 'fs'
function main() {
  const input = readFileSync('/dev/stdin', 'utf8')
  const [n, a, b, c] = input.trim().split('\n').map(v => v.split(' ').map(string => parseInt(string))) 
  console.log(n, a, b, c)
  let result = 0  
  for (let i = 0; i < a.length; i++) {
    const number = a[i] - 1
    result += b[number]
    if (number !== a.length && i + 1 !== a.length && a[i] + 1 === a[i + 1]) {
      result += c[number]
    }
  }
  console.log(result)
}
main()
//  [python]
S=input()
t=S[0::2].count('0')+S[1::2].count('1')
print(min(t,len(S)-t))
//  [python]
s = input()
c = s[::2].count("0") + s[1::2].count("1")
print(min(c, len(s)-c))
//  [python]
s = input()
h = s[::2].count('1') + s[1::2].count('0')
print(min(h, len(s)-h))
//  [python]
from collections import Counter
moji = str(input())
guall = len(moji)//2
kiall = guall + len(moji) % 2
gucount=dict(Counter(moji[1::2]))
kicount=dict(Counter(moji[0::2]))
if max(gucount, key=gucount.get) != max(kicount, key=kicount.get):
    ans = guall - max(gucount.values()) + kiall - max(kicount.values())
else:
    if kiall - max(kicount.values()) > guall - max(gucount.values()):
        ans = max(kicount.values()) + guall - max(gucount.values())
    else:
        ans = max(gucount.values()) + kiall - max(kicount.values())
print(ans)
//  [python]
s=input()
s=list(s)
c=0
for i in range(0,len(s)-1,2):
    if s[i]=='0':
        c+=1
    if s[i+1]=='1':
        c+=1
print(min(c,len(s)-c))
//  [python]
S = list(input())
ans = len(S)
for i in range(2):
  cnt = 0
  for j in range(ans):
    if j % 2 == 0 and S[j] != str(i): cnt += 1
    if j % 2 == 1 and S[j] == str(i): cnt += 1
  ans = min(ans,cnt)
print(ans)
//  [java]
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import static java.lang.Math.*;

public class Main {

	public static void main(String[] args) throws Exception {

		byte c;
		int x = 0, y = 0;
		boolean b = true;
		while ( (c = in.read()) != '\n' ) {
			if ( b && c == '1' || !b && c == '0' )
				x++;
			else
				y++;
			b = !b;
		}

		out.println(min(x, y));

	}


	static PrintStream out = System.out;
	static FastReader in = new FastReader();
}

class FastReader {
	final private int BUF_SIZE = 1 << 16;
	private DataInputStream din;
	private byte[] buffer = new byte[BUF_SIZE];
	private int bufferPointer, bytesRead;

	FastReader() {
		din = new DataInputStream(System.in);
	}

	String s() throws IOException {
		byte[] buf = new byte[64];
		int cnt = 0, c;
		while ((c = read()) != -1) {
			if (c == '\n') break;
			buf[cnt++] = (byte) c;
		}
		return new String(buf, 0, cnt);
	}

	int i() throws IOException {
		int ret = 0;
		byte c = read();
		while (c <= ' ') c = read();
		boolean neg = (c == '-');
		if (neg) c = read();
		do {
			ret = ret * 10 + c - '0';
		}
		while ((c = read()) >= '0' && c <= '9');
		return neg ? -ret : ret;
	}

	long l() throws IOException {
		long ret = 0;
		byte c = read();
		while (c <= ' ') c = read();
		boolean neg = (c == '-');
		if (neg) c = read();
		do {
			ret = ret * 10 + c - '0';
		}
		while ((c = read()) >= '0' && c <= '9');
		return neg ? -ret : ret;
	}

	double d() throws IOException {
		double ret = 0, div = 1;
		byte c = read();
		while (c <= ' ') c = read();
		boolean neg = (c == '-');
		if (neg) c = read();
		do {
			ret = ret * 10 + c - '0';
		}
		while ((c = read()) >= '0' && c <= '9');
		if (c == '.')
			while ((c = read()) >= '0' && c <= '9')
				ret += (c - '0') / (div *= 10);
		return neg ? -ret : ret;
	}

	private void fillBuffer() throws IOException {
		bytesRead = din.read(buffer, bufferPointer = 0, BUF_SIZE);
		if (bytesRead == -1) buffer[0] = -1;
	}

/*	private */ byte read() throws IOException {
		if (bufferPointer == bytesRead) fillBuffer();
		return buffer[bufferPointer++];
	}

	void close() throws IOException {
		if (din != null) din.close();
	}
}
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int ans0 = 0;
		int ans1 = 0;
		for (int i = 0; i < s.length(); i++) {
			int target = s.charAt(i)-'0';
			if ((target & 1)==0) {
				ans0++;
			}else {
				ans1++;
			}
		}
		System.out.println(Math.min(ans0, ans1));
	}

}
//  [cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX(x,y) (x>y?x:y)
#define MIN(x,y) (x<y?x:y)
#define ABS(x) (x>0?x:-(x))

#define INF 1000000000

int array_min_max(int* p, int n,bool f)  //f: true→min false→max
{
	int tmp;

	if (f)
		tmp = INF;
	else
		tmp = 0;

	for (int i = 0; i < n; i++)
	{
		if (f)
		{
			if (p[i] < tmp)
				tmp = p[i];
		}
		else
		{
			if (p[i] > tmp)
				tmp = p[i];
		}
	}
	return tmp;
}

int main()
{
	char S[100000];
	int count = 0;
	int count2=0;

	scanf("%s", S);

	for (int i = 0; S[i]!=NULL; i++)
	{
		if (i % 2 == 0)
		{
			if (S[i] == '1')
				count++;
		}
		else
		{
			if (S[i] == '0')
				count++;
		}

	}

	for (int i = 0; S[i] != NULL; i++)
	{
		if (i % 2 == 0)
		{
			if (S[i] == '0')
				count2++;
		}
		else
		{
			if (S[i] == '1')
				count2++;
		}

	}

	printf("%d\n", MIN(count, count2));
}