//author: hitch_hiker42;
#include<bits/stdc++.h>
using namespace std;

//solution:
#define int int64_t
#define span(a) begin(a), end(a)
constexpr int mod = 1e9 + 7;

void hike() {
  int n; cin >> n;
  vector<int> a(n);
  for(int& i: a) {
    cin >> i;
  }
  if(n == 1) {
    cout << a[0] << "\n";
    return;
  }
  int dp[n][2], p[n][2];
  memset(dp, 0, sizeof dp);
  memset(p, 0, sizeof p);
  dp[1][0] = a[0] - a[1];
  dp[1][1] = a[0] + a[1];
  p[1][0] = p[1][1] = 1;
  for(int i = 2; i < n; ++i) {
    dp[i][0] = ((dp[i - 1][1] - p[i - 1][1] * a[i] % mod) % mod + mod) % mod;
    dp[i][1] = ((dp[i - 1][0] + dp[i - 1][1]) % mod + (p[i - 1][0] + p[i - 1][1]) * a[i] % mod) % mod;
    p[i][0] = p[i - 1][1];
    p[i][1] = (p[i - 1][0] + p[i - 1][1]) % mod;
  }
  cout << (dp[n - 1][0] + dp[n - 1][1]) % mod << "\n";
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr); cout.tie(nullptr);
  int t = 1; //cin >> t;
  while(t--) hike();
  return 0;
} //farewell, until we meet again..

#include <bits/stdc++.h>

using namespace std;

using i8 = int8_t;
using i16 = int16_t;
using i32 = int32_t;
using i64 = int64_t;
using isize = ptrdiff_t;

using u8 = uint8_t;
using u16 = uint16_t;
using u32 = uint32_t;
using u64 = uint64_t;
using usize = size_t;

using f32 = float_t;
using f64 = double_t;

template <typename T> using vec = vector<T>;
template <typename T> using vec_deq = deque<T>;
template <typename T> using linked_list = list<T>;

template<typename T> using hash_set = unordered_set<T>;
template<typename T> using btree_set = set<T>;

template<typename K, typename V> using hash_map = unordered_map<K, V>;
template<typename K, typename V> using btree_map = map<K, V>;

template<typename T> using max_heap = priority_queue<T>;
template<typename T> using min_heap = priority_queue<T, vec<T>, greater<T>>;

template<typename T> using fn = function<T>;

mt19937 rng(chrono::system_clock::now().time_since_epoch().count());

namespace mod {
    template<typename Tp>
    inline Tp pow(Tp x, u64 y) {
        Tp r = (Tp)1;
        while (y) {
            if (y & 1) r = r * x;
            x = x * x, y >>= 1;
        }
        return r;
    }

    constexpr bool is_prime(i64 n) {
        if (n == 1) return false;
        if ((n & 1) == 0) return n == 2;

        for (i64 i = 3; i * i <= n; i += 2) {
            if (n % i == 0) return false;
        }
        return true;
    }

    template<i64 M>
    class modular {
    private:
        static_assert(is_prime(M) == true, "M is not a prime number");
        i64 value;

        modular inv() const { return pow(*this, M - 2); }
    public:
        modular() : value(0) {}
        modular(i64 rr) : value(rr) { value %= M; if (value < 0) value += M; }

        inline modular operator * (const modular& t) const { return (value * t.value) % M; }
        inline modular operator / (const modular& t) const { return *this * t.inv(); }
        inline modular operator + (const modular& t) const { return modular(*this) += t; }
        inline modular operator - (const modular& t) const { return modular(*this) -= t; }

        inline modular operator += (const modular& t) { value += t.value; if (value >= M) value -= M; return *this; }
        inline modular operator -= (const modular& t) { value -= t.value; if (value < 0) value += M; return *this; }
        inline modular operator *= (const modular& t) { return *this = *this * t; }
        inline modular operator /= (const modular& t) { return *this = *this / t; }

        inline bool operator == (const modular& t) const { return value == t.value; }
        inline bool operator != (const modular& t) const { return value != t.value; }

        inline operator i64() const { return value; }

    };
}

typedef mod::modular<1000000007> mint;
// typedef mod::modular<998244353> MInt;

auto main() -> i32 {

    ios::sync_with_stdio(false), cin.tie(nullptr);

    i32 n;
    cin >> n;
    vec<mint> pls(n + 1), mis(n + 1);
    vec<i32> a(n + 1);

    pls[0] = 1;
    mis[0] = 0;

    for (i32 i = 1; i <= n; i++) {
        cin >> a[i];

        pls[i] = pls[i - 1] + mis[i - 1];
        mis[i] = pls[i - 1];

    }

    mint ans = 0;
    for (i32 i = 1; i <= n; i++) {
        if (i > 1) {
            ans += mint(a[i]) * (pls[n - i] + mis[n - i]) * (pls[i - 2] + mis[i - 2]);
            if (i > 2 && i < n)
                ans -= mint(a[i]) * (pls[n - i - 1] + mis[n - i - 1]) * (pls[i - 3] + mis[i - 3]);

            if (n > 2) {
                if (i == 2)
                    ans -= mint(a[i]) * (pls[n - i - 1] + mis[n - i - 1]) * (mint(1));
                else if (i == n)
                    ans -= mint(a[i]) * (pls[n - 3] + mis[n - 3]);
            }
            else {
                ans -= mint(a[i]);
            }
        }
        else {
            ans += mint(a[i]) * (pls[n - 1] + mis[n - 1]);
        }
    }

    cout << i64(ans);
    cout << "\n";
    return 0;
}


#include <iostream>
using namespace std;

using ll = long long;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    ll n_odd = 0;
    bool odd;
    cin >> n >> m;
    string s;
    for(int i = 0; i < n; i++) {
        cin >> s;
        odd = 0;
        for(char c : s) {
            if(c == '1') {
                odd = !odd;
            }
        }
        n_odd += odd;
    }
    cout << n_odd * (n - n_odd);
    return 0;
}

#include "bits/stdc++.h"
using namespace std;
using ll=int64_t;
using ld=long double;
using ull=unsigned long long;
template <class T>
using grid=vector<vector<T>>;
#define ALL(x) x.begin(),x.end()
#define rep(iter,from,to) for(ll iter=from;iter<to;++iter)

const ll MOD = 1e9 + 7;
const ll INF = 1e17;
//#######################################################################
vector<vector<ll>> input(ll N, ll width) {
    string str;
    vector<vector<ll>> vec(N, vector<ll>(width));
    for (ll i = 0; i < N; ++i) {
        cin >> str;
        reverse(ALL(str));
        for (ll j = 0; j < width; ++j) {
            vec[i][j] = str.back();
            str.pop_back();
        }
    }
    return vec;
}
void op(vector<ll> vec) {
    ll size = (ll)vec.size();
    for (ll i = 0; i < size - 1; ++i) cout << vec[i] << " ";
    cout << vec.back() << endl;
}

void op(vector<vector<ll>> vec) {
    ll height = (ll)vec.size();
    ll width = (ll)vec[0].size();
    for (ll i = 0; i < height; ++i) {
        for (ll j = 0; j < width - 1; ++j) cout << vec[i][j] << " ";
        cout << vec[i].back() << endl;
    }
}
//########################################################################

int solve(){
    ll N,M;
    cin>>N>>M;
    vector<pair<ll,string>> dict;
    rep(i,0,M){
        string s;
        cin>>s;
        dict.emplace_back(s.size(),s);
    }
    grid<char> res(N,vector<char>(N,'.'));
    sort(ALL(dict));
    string use=dict.front().second;
    for(ll i=0;i<N;++i) {
        ll iter=0;
        ll start=0;
        while(true){
            rep(j,0,dict[0].first) {
                res[i][start+j]=dict[0].second[j];
            }
            start+=dict[0].first;
            if(start+dict[0].first>=N-1) break;
        }
    }
    rep(i,0,N) {
        rep(j,0,N) cout<<res[i][j];
        cout<<endl;
    }
    return 0;
}

int main(void){
    std::cin.tie(nullptr);
	std::ios_base::sync_with_stdio(false);
	std::cout << std::fixed << std::setprecision(15);
	solve();
}


#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (n); i++)
#define loop(i, a, n) for(int i = (a); i < (n); i++)
#define all(x) x.begin(), x.end()
#ifdef _DEBUG
#define disp(x) cout << #x << " : " << x << endl
#else
#define disp(x)
#endif
using namespace std;
using ll = int64_t;

ll mod_pow(ll x, ll n, const ll mod){
    ll ans = 1;
    while(n){
        if(n & 1) ans = ans*x%mod;
        x = x*x%mod;
        n >>= 1;
    }
    return ans;
}

int main(){
    ll n, m; cin >> n >> m;
    const ll mod = m*m;

    ll ans = mod_pow(10, n, mod);
    ans /= m;
    ans %= m;
    cout << ans << endl;

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define rep1(i,n) for(ll i=1;i<=(ll)(n);i++)

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

  int n,m;
  cin >> n >> m;
  ll max = 1e8;
  if(n==1 && m==0){
    cout << 1 <<" " << 2 << endl;
  }
  else if(n==m || n-1==m || m<0){
    cout << -1 << endl;
  }
  else {
    int l = 2;
    int ok_cnt=2;
    rep(i,n-1){
      cout << l <<" " << l+1 << endl;
      if(n-m==ok_cnt){
        cout << l-1 << " " << max << endl;
      }
      else if(i==n-2 && n-m>ok_cnt){
        cout << max-10 <<" " << max << endl;
      }
      l+=3;
      ok_cnt++;

    }

  }
  return 0;

}


//clear adj and visited vector declared globally after each test case
//check for long long overflow
//Mod wale question mein last mein if dalo ie. Ans<0 then ans+=mod;
//Incase of close mle change language to c++17 or c++14
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);cout.precision(dbl::max_digits10);
#define pb push_back
#define mod 1000000007ll //998244353ll
#define lld long double
#define mii map<int, int>
#define pii pair<int, int>
#define ll long long
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rep(i,x,y) for(int i=x; i<y; i++)
#define fill(a,b) memset(a, b, sizeof(a))
#define vi vector<int>
#define setbits(x) __builtin_popcountll(x)
#define print2d(dp,n,m) for(int i=0;i<=n;i++){for(int j=0;j<=m;j++)cout<<dp[i][j]<<" ";cout<<"\n";}
typedef std::numeric_limits< double > dbl;
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
//member functions :
//1. order_of_key(k) : number of elements strictly lesser than k
//2. find_by_order(k) : k-th element in the set
const long long N=2000005, INF=2000000000000000000;
lld pi=3.1415926535897932;
int lcm(int a, int b)
{
    int g=__gcd(a, b);
    return a/g*b;
}
int power(int a, int b, int p)
    {
        if(a==0)
        return 0;
        int res=1;
        a%=p;
        while(b>0)
        {
            if(b&1)
            res=(res*a)%p;
            b>>=1;
            a=(a*a)%p;
        }
        return res;
    }
int fact[N],inv[N];
void pre()
{
    fact[0]=1;
    inv[0]=1;
    for(int i=1;i<N;i++)
    fact[i]=(i*fact[i-1])%mod;
    for(int i=1;i<N;i++)
    inv[i]=power(fact[i], mod-2, mod);
}
int nCr(int n, int r, int p)
{
    if(r>n)
    return 0;
    if(n==r)
    return 1;
    if (r==0)
    return 1;
    return (((fact[n]*inv[r]) % p )*inv[n-r])%p;
}

int32_t main()
{
    IOS;
    pre();
    int n, m, k;
    cin>>n>>m>>k;
    int ans=0;
    rep(i,max(0ll, n-m),k+1)
    {
        ans+=(nCr(n+m, m+i, mod) - nCr(n+m, m+i+1, mod) + mod)%mod;
        ans%=mod;
    }
    cout<<ans;
}

#include<bits/stdc++.h>
#define int long long
const int mod=1e9+7;
using namespace std;
int qpow(int a,int b){
	int ans=1;
	while(b){
		if(b&1)(ans*=a)%=mod;
		(a*=a)%=mod;
		b>>=1;
	}
	return ans;
}
int inv(int a){
	return qpow(a,mod-2);
}
int fact(int a){
	int ans=1;
	for(int i=1;i<=a;i++){
		(ans*=i)%=mod;
	}
	return ans;
}
int cc(int a,int b){
	if(a<0||b<0)return 0;
	return fact(b)*inv(fact(b-a))%mod*inv(fact(a))%mod;
}
signed main(){
	int n,m,k;
	cin>>n>>m>>k;
	if(n>m+k){
		cout<<0;
	}
	else cout<<((cc(n,n+m)-cc(n-k-1,m+n))%mod+mod)%mod;
}


#ifndef LOCAL
#include <bits/stdc++.h>
using namespace std;
#define debug(...) 42
#else
#include "Debug.hpp"
#endif

class Task {
 public:
  void Perform() {
    Read();
    Solve();
  }

 private:
  int a, b, c, d;

  void Read() {
    cin >> a >> b >> c >> d;
  }

  void Solve() {
    int max_diff = INT_MIN;
    for (int x = a; x <= b; ++x) {
      for (int y = c; y <= d; ++y) {
        max_diff = max(max_diff, x - y);
      }
    }
    cout << max_diff << '\n';
  }
};

int main() {
  ios_base::sync_with_stdio(false), cin.tie(nullptr);
  Task t;
  t.Perform();
  return 0;
}

#include <bits/stdc++.h>

#define int      long long int

using namespace std;

void solve();

int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    solve();

    return 0;
}

void solve()
{
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    cout<<b-c<<endl;
}


#include<bits/stdc++.h>
using namespace std;
const int M = 1e9 + 7;
const int MAX = 1e5 + 5;
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define int long long int
#define pb push_back
#define print(x) cout<<x<<"\n"
#define time_passed	1.0 * clock() / CLOCKS_PER_SEC

//basic mathematics
int gcd(int a, int b)
{
	if (a == 0)
		return b;
	return gcd(b % a, a);
}
int lcm(int a, int b)
{
	return (a * b) / gcd(a, b);
}

//modular arithmetic
int powermod(int x, int y, int p)
{
	int res = 1;

	x = x % p;

	if (x == 0) return 0;

	while (y > 0)
	{
		if (y & 1)
			res = (res * x) % p;
		y = y >> 1;
		x = (x * x) % p;
	}
	return res;
}

//SOURCE GEEKS FOR GEEKS
bool solve(string n, int l)
{

    // Less than three digit number
    // can be checked directly.
    if (l < 3) {
        if (stoi(n) % 8 == 0)
            return true;

        // check for the reverse of a number
        reverse(n.begin(), n.end());
        if (stoi(n) % 8 == 0)
            return true;
        return false;
    }

    // Stores the Frequency of characters in the n.
    int hash[10] = { 0 };
    for (int i = 0; i < l; i++)
        hash[n[i] - '0']++;

    // Iterates for all three digit numbers
    // divisible by 8
    for (int i = 104; i < 1000; i += 8) {

        int dup = i;

        // stores the frequency of all single
        // digit in three-digit number
        int freq[10] = { 0 };
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;

        dup = i;

        // check if the original number has
        // the digit
        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;

        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;

        if (freq[dup % 10] > hash[dup % 10])
            continue;

        return true;
    }

    // when all are checked its not possible
    return false;
}

void solve()
{
    string s;
    cin >> s;
    if (solve(s, s.size()))
        cout << "Yes";
    else
        cout << "No";

}

int32_t main(void)
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	fastio
	int t = 1;
	//cin >> t;
	while (t--)
	{
		solve();
	}
	cerr << "\n" << "Time elapsed : " << time_passed << "\n";
	return 0;
}

#include <bits/stdc++.h>

typedef long double ld;
#define int long long

#define gcd            __gcd
#define endl           "\n"
#define setbits(x)     __builtin_popcountll(x)
#define zrobits(x)     __builtin_ctzll(x)
#define mod            1000000007
#define mod2           998244353
#define maxe           *max_element
#define mine           *min_element
#define inf            1e18
#define pb             push_back
#define all(x)         x.begin(), x.end()
#define f              first
#define s              second
#define lb             lower_bound
#define ub             upper_bound
#define ins            insert
#define sz(x)          (int)(x).size()
#define mk             make_pair
#define deci(x, y)     fixed<<setprecision(y)<<x
#define w(t)           int t; cin>>t; while(t--)
#define nitin          ios_base::sync_with_stdio(false); cin.tie(nullptr)
#define PI             3.141592653589793238
#define mem0(x)        memset(x,0,sizeof x)
#define mem1(x)        memset(x,-1,sizeof x)
using namespace std;
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.f << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }

void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }

#ifdef NITIN
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
vector<int> solve(vector<int>&a,vector<int>&b) {
    vector<int> temp;
    for (auto &c:a) {
        auto idx = lower_bound(all(b), c);
        int op1 = inf, op2 = inf;
        if (idx != b.end()) {
            op1 = min(op1, abs(*idx - c));
        }
        if (idx != b.begin()) {
            idx = prev(idx);
            op2 = min(op2, abs(*idx - c));
        }
        temp.push_back(min(op1, op2));
    }
    return temp;
}

void solve() {
    int n;
    cin>>n;
    vector<int>r,g,b;
    for(int i=0;i<2*n;i++) {
        int val;
        cin >> val;
        char col;
        cin >> col;
        if (col == 'R') {
            r.pb(val);
        } else if (col == 'G') {
            g.pb(val);
        } else {
            b.pb(val);
        }
    }
    sort(all(r));
    sort(all(g));
    sort(all(b));
    if(r.size()%2==0 && g.size()%2==0 && b.size()%2==0){
        cout<<0<<endl;
    }else{
        if(r.size()%2!=0) {
            if (b.size() % 2 == 0) {
                swap(r, b);
            } else {
                swap(r, g);
            }
        }
        int ans=inf;
        vector<int> temp=solve(g,b);
        ans=mine(all(temp));
        vector<int>fir=solve(r,g);
        vector<int>sec=solve(r,b);
        map<int,int>take;
        for(auto &c:sec)
            take[c]++;
        for(int i=0;i<r.size();i++) {
            take[sec[i]]--;
            if (take[sec[i]] == 0) {
                take.erase(sec[i]);
            }
            ans = min(ans, fir[i] + take.begin()->first);
            take[sec[i]]++;
        }
        cout<<ans<<endl;
    }
}

int32_t main() {
    nitin;

    solve();
}


// Jai Shree Ram

#include<bits/stdc++.h>
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define ook order_of_key
#define fbo find_by_order

#define rep(i,a,n)     for(int i=a;i<n;i++)
#define ll             long long
#define int            long long
#define pb             push_back
#define all(v)         v.begin(),v.end()
#define endl           "\n"
#define x              first
#define y              second
#define gcd(a,b)       __gcd(a,b)
#define mem1(a)        memset(a,-1,sizeof(a))
#define mem0(a)        memset(a,0,sizeof(a))
#define sz(a)          (int)a.size()
#define pii            pair<int,int>
#define hell           1000000007
#define elasped_time   1.0 * clock() / CLOCKS_PER_SEC

template<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}
template<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<" "<<a.y;return out;}
template<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}
template<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}

const int N=1e9+5;
const int M=1e7;

struct node{
	int l;int r;
	int val;
	int cnt;
}t[M];
int cnt=0;

int n;

void extend(int v){
	if(t[v].l==0){
		t[v].l=++cnt;
		t[v].r=++cnt;
	}
}

void pushup(int v){
	t[v].val = t[t[v].l].val + t[t[v].r].val;
	t[v].cnt = t[t[v].l].cnt + t[t[v].r].cnt;
}

void update(int v,int l,int r,pii val,int tl=0,int tr=1e9){
	if(tl>r || l>tr)return;
	if(l<=tl && tr<=r){
		assert(tl == tr);
		t[v].val += val.x;
		t[v].cnt += val.y;
		return;
	}
	extend(v);
	int mid=(tl+tr)/2;
	update(t[v].l,l,r,val,tl,mid);
	update(t[v].r,l,r,val,mid+1,tr);
	pushup(v);
}

pii query(int v,int l,int r,int tl=0,int tr=1e9){
	if(tl>r || l>tr)return {0,0};
	if(l<=tl && tr<=r){
		return {t[v].val,t[v].cnt};
	}
	int mid=(tl+tr)/2;
	extend(v);
	pii a =query(t[v].l,l,r,tl,mid);
	pii b =query(t[v].r,l,r,mid+1,tr);
	return {a.x+b.x,a.y+b.y};
}

int solve(){
		int n,m,q; cin >> n >> m >> q;

		int ans = 0;
		int roota = ++cnt;
		int rootb = ++cnt;

		vector<int>v1(n+1),v2(m+1);
		update(roota,0,0,{0,n});
		update(rootb,0,0,{0,m});

		rep(i,0,q){
			int t; cin >> t;
			int x,y; cin >> x >> y;
			if(t == 1){
				if(y > v1[x]){
					auto s = query(rootb,0,y);
					ans += s.y*y;
					s = query(rootb,v1[x]+1,y);
					ans -= s.x;
					s = query(rootb,0,v1[x]);
					ans -= v1[x]*s.y;
				}
				else if(y < v1[x]){
					auto s = query(rootb,0,v1[x]);
					ans -= s.y*v1[x];
					s = query(rootb,0,y);
					ans += s.y*y;
					s = query(rootb,y+1,v1[x]);
					ans += s.x;
				}
				update(roota,v1[x],v1[x],{-v1[x],-1});
				update(roota,y,y,{y,1});
				v1[x] = y;
			}
			else{
				if(y > v2[x]){
					auto s = query(roota,0,y-1);
					ans += s.y*y;
					s = query(roota,0,v2[x]-1);
					ans -= s.y*v2[x];
					s = query(roota,v2[x],y-1);
					ans -= s.x;
				}
				else if(y < v2[x]){
					auto s = query(roota,0,v2[x]-1);
					ans -= s.y*v2[x];
					s = query(roota,0,y-1);
					ans += s.y*y;
					s = query(roota,y,v2[x]-1);
					ans += s.x;
				}
				update(rootb,v2[x],v2[x],{-v2[x],-1});
				update(rootb,y,y,{y,1});
				v2[x] = y;
			}
			cout << ans << endl;
		}
 return 0;
}
signed main(){
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #ifdef SIEVE
    sieve();
    #endif
    #ifdef NCR
    init();
    #endif
    int t=1;//cin>>t;
    while(t--){
        solve();
    }
    return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<iomanip>
#include<cmath>
#include<numeric>
#include<vector>
#include<algorithm>
#include<string>
#include<deque>
#include<stack>
#include<map>
#include<random>
#include<queue>
#include<iterator>
#include<bitset>
#include<unordered_set>
#include<set>

using namespace std;
#define ll long long
#define endl "\n"
const int dx[] = { 1 ,0, -1, 0 };
const int dy[] = { 0, 1, 0, -1 };
const int N = 1e6 + 100;
const int NN = 1e3 + 100;
#define TC int t;cin>>t;for(int T=1;T<=t;T++)
#define mod 1000000007
#define PI acos(-1) // 3.141592654
#define EPS 0.000000001
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define mem(a,n) memset(a,n,sizeof(a))
#define sz(x) x.size()
void AIA() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
//cout<<fixed<<setprecision(20);
//freopen("stand.in","r",stdin);
//freopen("stand.out","w",stdout);
//priority_queue<ll, vector<ll>, greater<ll>>p2;

bool isprime(ll n) {
	for (ll i = 2; i * i <= n; i++) {
		if (n % i == 0)return 0;
	}
	return (n != 1);
}
ll gcd(ll x, ll y)
{
	return (y == 0 ? x : gcd(y, x % y));
}
ll lcm(ll x, ll y) {
	return (x * y) / gcd(x, y);
}
ll nCr(ll n, ll r) {
	ll ans = 1;
	ll div = 1; // r!
	for (ll i = r + 1; i <= n; i++) {
		ans = ans * i;
		ans /= div;
		div++;
	}
	return ans;
}
ll NpR(ll n, ll r) {
	ll ans = 1;
	for (ll i = (n - r) + 1; i <= n; i++) {
		ans *= i;
		ans %= mod;
	}
	return ans;
}

/*
 _____________              __                ___        ___       ___________________________     ____        ____
|             |            /\ \              |   |      |   |     |                           |    \   \      /   /
|   __________|           / /\ \             |   |      |   |     |      _____      _____     |     \   \    /   /
|  |                     / /  \ \            |   |      |   |     |     |     |    |     |    |      \   \  /   /
|  |                    / /    \ \           |   |      |   |     |     |     |    |     |    |       \   \/   /
|  |______             / /      \ \          |   |______|   |     |     |     |    |     |    |        \      /
|         |           / /        \ \         |              |     |     |     |    |     |    |         \    /
|   ______|          / /          \ \        |    ______    |     |     |     |    |     |    |          |  |
|  |                / /============\ \       |   |      |   |     |     |     |    |     |    |          |  |
|  |               / /==============\ \      |   |      |   |     |     |     |    |     |    |          |  |
|  |              / /                \ \     |   |      |   |     |     |     |    |     |    |          |  |
|  |             / /                  \ \    |   |      |   |     |     |     |    |     |    |          |  |
|__|            /_/                    \_\   |___|      |___|     |_____|     |____|     |____|          |__|

										  <<<<<<<<<<< NEVER GIVE UP !! >>>>>>>>>>>
										<<<<<<<< YOU CAN DO IT IF YOU WANT !! >>>>>>>>
										 <<<<<<<<< BELIEVE IN YOURSELF !! >>>>>>>>>

*/
int main() {
	//cout << fixed << setprecision(0);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	AIA();
	int a, b, c, d;
	cin >> a >> b >> c >> d;
	cout << (a * d) - (b * c);
	return 0;
}


#include <bits/stdc++.h>

#pragma region ppd
#define ll long long
#define ld long double
#define mp make_pair
#define mt make_tuple
#define ff first
#define ss second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define for0(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define forr(i, n) for (int i = (int)(n)-1; i >= 0; --i)
#define forab(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
#define foriter(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define endl '\n'
#define INF (ll)(1e9)
#define EPS 1e-9
#define MOD (ll)(1e9 + 7)
#define PI 3.1415926535897932384626433832795
#define set set
#define mset multiset
#define uset unordered_set
#define umset unordered_multiset
#define map map
#define mmap multimap
#define umap unordered_map
#define ummap unordered_multimap
#define FILEIO                        \
    freopen("input.txt", "r", stdin); \
    freopen("output.txt", "w", stdout);

using namespace std;

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vll;
typedef vector<vll> vvll;
typedef pair<i64, i64> pll;

template <class T>
bool ckmin(T &a, const T &b) { return b < a ? a = b, 1 : 0; }
template <class T>
bool ckmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }

template <class T> void re(T &x) { cin >> x; }
template <class Arg, class... Args> void re(Arg &first, Args &...rest) { re(first); re(rest...); }
template <class T> void re(vector<T> &a) { for0(i, a.size()) re(a[i]); }

template <class T> void pr(T &x) { cout << x << " "; }
template <class Arg, class... Args> void pr(Arg &first, Args &...rest) { pr(first); pr(rest...); }
template <class T> void pr(vector<T> &a) { for0(i, a.size()) pr(a[i]); }

#pragma endregion ppd

//=============================================================================//
ll g1(ll n) {
    mset<ll, greater<ll>> s;
    while(n) {
        s.insert(n%10);
        n/=10;
    }
    ll ret = 0;
    for(auto &d: s) {
        ret = ret*10 + d;
    }

    return ret;
}

ll g2(ll n) {
    mset<ll> s;
    while(n) {
        s.insert(n%10);
        n/=10;
    }
    ll ret = 0;
    for(auto &d: s) {
        ret = ret*10 + d;
    }

    return ret;
}

void solve()
{
    ll n, k; re(n, k);

    for0(i, k) {
        ll newn = g1(n) - g2(n);
        //cout<<endl<<endl;
        n = newn;
    }

    pr(n);
}

int main()
{
#ifndef ONLINE_JUDGE
    FILEIO
    auto start = chrono::high_resolution_clock::now();
#endif
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.precision(10);
    //==================================================================================

    int T = 1;
    //cin >> T;
    while (T--)
    {
        solve();
        cout << endl;
    }

//==================================================================================
#ifndef ONLINE_JUDGE
    auto finish = chrono::high_resolution_clock::now();

    chrono::duration<double> elapsed = finish - start;
    cout << "\nTime: " << elapsed.count() << " s\n";
#endif

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int n,k,nn,minn,maxx;
string nts(int x)
{
	string res="";
	while(x)
	{
		res=(char)(x%10+'0')+res;
		x/=10;
	}
	return res;
}
int stn(string x)
{
	int res=0;
	for(int i=0;i<x.size();i++)
	{
		res*=10;
		res+=x[i]-'0';
	}
	return res;
}
int main()
{
	cin>>n>>k;
	for(int i=0;i<k;i++)
	{
		string s=nts(n);
		sort(s.begin(),s.end());
		minn=stn(s);
		reverse(s.begin(),s.end());
		maxx=stn(s);
		nn=maxx-minn;
		if(nn==n)
		{
			cout<<n;
			return 0;
		}
		n=nn;
	}
	cout<<n;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define ll long long

#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define fill(a,b) memset(a,b,sizeof(a))

#define f first
#define s second
#define pb push_back

#define inf 1e17
#define ninf -1*1e17
#define mod 1000000007
#define N 500005
#define Ns 5005
#define hsum 600000
string s;
ll n,m,o,x,y,z,d,k,l,r;
ll a[N];

ll dp[102][hsum];
int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

	int t=1;
	//cin>>t;
	while(t--){

	   // ll ans=0;
	    cin>>n>>k>>m;

	    dp[0][0]=1;
	    //dp[1][1]=1;
	    for(int i=1;i<=n;i++){
	        for(int j=0;j<=hsum;j++){
	            ll cnt=0;
	            if(j-i>=0){
	                cnt=(cnt+dp[i][j-i])%m;
	            }
	            if(i-1>=0){
	                cnt=(cnt+dp[i-1][j])%m;
	            }
	            if(i-1>=0 && (j-(k+1)*i) >=0){
	                cnt=(cnt-dp[i-1][j-(k+1)*i]+m)%m;
	            }
	            dp[i][j]=cnt;
	            //cout<<dp[i][j]<<" ";
	        }
	        //cout<<"\n";
	    }

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

	        ll ans=0;
	        for(int j=1;j<=hsum;j++){
	            if(i-1>=0 && n-i >=0)
	             ans=(ans+(dp[i-1][j]*dp[n-i][j])%m)%m;
	        }
	        ans=(ans*(k+1))%m;
	        ans=(ans-1+m)%m;
	        cout<<ans<<"\n";
	    }

	    //cout<<ans<<"\n";

	}
	return 0;
}

#include <bits/stdc++.h>
using namespace std;

// ModIntR::set_mod()
struct ModIntR {
  int x;
  ModIntR() : x(0) {}
  ModIntR(int64_t y) : x(y >= 0 ? y % mod() : (mod() - (-y) % mod()) % mod()) {}
  static int &mod() {
    static int mod = 0;
    return mod;
  }
  static void set_mod(int md) { mod() = md; }
  ModIntR &operator+=(const ModIntR &p) {
    if ((x += p.x) >= mod()) x -= mod();
    return *this;
  }
  ModIntR &operator-=(const ModIntR &p) {
    if ((x += mod() - p.x) >= mod()) x -= mod();
    return *this;
  }

  ModIntR &operator*=(const ModIntR &p) {
    long long m = mod();
    x = (int)(1LL * x * p.x % m);
    return *this;
  }

  ModIntR &operator/=(const ModIntR &p) {
    *this *= p.inverse();
    return *this;
  }

  ModIntR operator-() const { return ModIntR(-x); }

  ModIntR operator+(const ModIntR &p) const { return ModIntR(*this) += p; }

  ModIntR operator-(const ModIntR &p) const { return ModIntR(*this) -= p; }

  ModIntR operator*(const ModIntR &p) const { return ModIntR(*this) *= p; }

  ModIntR operator/(const ModIntR &p) const { return ModIntR(*this) /= p; }

  bool operator==(const ModIntR &p) const { return x == p.x; }

  bool operator!=(const ModIntR &p) const { return x != p.x; }

  ModIntR inverse() const {
    int a = x, b = mod(), u = 1, v = 0, t;
    while (b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModIntR(u);
  }

  ModIntR pow(int64_t n) const {
    ModIntR res(1), mul(x);
    while (n) {
      if (n & 1) res *= mul;
      mul *= mul;
      n >>= 1;
    }
    return res;
  }

  friend ostream &operator<<(ostream &os, const ModIntR &p) {
    return os << p.x;
  }

  friend istream &operator>>(istream &is, ModIntR &a) {
    int64_t t;
    is >> t;
    a = ModIntR(t);
    return (is);
  }
};

int n, k, m, ofst = 2e6, len;
vector<ModIntR> cnt, memo;

void add(int x);
void sub(int x);
bool isvalid(int x) { return -len + ofst <= x && x <= len + ofst; }

int main() {
  cin >> n >> k >> m;
  len = n * (n + 1) / 2 * k;
  ModIntR::set_mod(m);
  cnt.assign((int)4e6, 0);
  memo.assign((int)4e6, 0);
  cnt[ofst] = 1;
  for (int i = 1; i <= n; ++i) add(i);
  for (int i = 1; i <= n; ++i) {
    // for (int j = -6; j <= 6; ++j) cout << cnt[j + ofst] << " ";
    // cout << endl;
    if (n + 1 - i != 0) sub(n + 1 - i);
    // for (int j = -6; j <= 6; ++j) cout << cnt[j + ofst] << " ";
    // cout << endl;
    cout << (cnt[ofst] * (k + 1)) - 1 << endl;
    add(-i);
    // for (int j = -6; j <= 6; ++j) cout << cnt[j + ofst] << " ";
    // cout << endl;
  }
  return 0;
}

void add(int x) {
  vector<ModIntR> sum(abs(x), 0);
  int sign = x / abs(x);
  x = abs(x);
  for (int i = -len * sign + ofst; isvalid(i); i += sign) {
    sum[i % x] -= memo[i];
    memo[i] = 0;
    ModIntR tmp = sum[i % x];
    sum[i % x] += cnt[i];
    if (isvalid(i + sign * x * (k + 1))) memo[i + sign * x * (k + 1)] = cnt[i];
    cnt[i] += tmp;
  }
}
void sub(int x) {
  vector<ModIntR> sum(abs(x), 0);
  int sign = x / abs(x);
  x = abs(x);
  for (int i = -len * sign + ofst; isvalid(i); i += sign) {
    sum[i % x] -= memo[i];
    memo[i] = 0;
    ModIntR tmp = sum[i % x];
    cnt[i] -= tmp;
    sum[i % x] += cnt[i];
    if (isvalid(i + sign * x * (k + 1))) memo[i + sign * x * (k + 1)] = cnt[i];
  }
}


#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(a) (a).begin(),(a).end()

template<typename T1, typename T2> inline void chkmin(T1 & x, const T2 & y) {if (y < x) x = y;}
template<typename T1, typename T2> inline void chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

void no() {
    cout << "No\n";
    exit(0);
}

const int N = 210;
int n;
int a[N], b[N];

void read() {
    cin >> n;
    set<int> setik;
    for (int i = 0; i < n; ++i) {
        cin >> a[i] >> b[i];
        if (a[i] != -1 && setik.count(a[i])) no();
        if (b[i] != -1 && setik.count(b[i])) no();
        setik.insert(a[i]);
        setik.insert(b[i]);
    }
}

bool used[N];

bool check(int l, int r) {
    //l = 2 * l + 1;
    //r = 2 * r;
    //cout << "l = " << l << " r = " << r << endl;
    if (r <= l) return false;
    if ((r - l + 1) % 2) return false;
    fill(used, used + N, false);
    int c = (r - l + 1) / 2;
    //cout << "c = " << c << endl;
    for (int i = 0; i < n; ++i) {
        int x = a[i], y = b[i];
        //cout << "x = " << x << " y = " << y << endl;
        if (x == -1 && y == -1) continue;
        if (x != -1 && y != -1 && x >= y) return false;
        bool must = (x >= l && x <= r) || (y >= l && y <= r);
        if (x == -1) {
            x = y - c;
        } else if (y == -1) {
            y = x + c;
        }
        if (x > r || y < l) continue;
        if ((x < l || y > r) && must) return false;
        if ((x < l || y > r)) continue;
        if (y - x != c) return false;
        if (used[x] || used[y]) return false;
        //cout << "x = " << x << "y = " << y << endl;
        used[x] = true;
        used[y] = true;
    }
    return true;
}

bool dp[N];

void calcDp() {

    //cout << check(1, 4) << endl;
    //exit(0);
    /*cout << check(1, 3) << endl;
    exit(0);
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j <= n; ++j) {
            cout << check(i, j) << " ";
        }
        cout << endl;
    }*/
    //exit(0);
    dp[0] = 1;
    for (int i = 1; i <= 2 * n; ++i) {
        for (int j = 0; j < i; ++j) {
            dp[i] |= dp[j] && check(j + 1, i);
        }
    }
}

void run() {
    calcDp();
}

void write() {
    if (!dp[2 * n]) {
        no();
    }
    cout << "Yes\n";
}

signed main() {
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout.precision(20), cout.setf(ios::fixed);
    read();
    run();
    write();
    return 0;
}

#include<bits/stdc++.h>
using namespace std;

#define GO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long int
#define endl "\n"
const int maxr = 1e6 + 5;

int gcd(int a, int b, int& x, int& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int x1, y1;
    int d = gcd(b, a % b, x1, y1);
    x = y1;
    y = x1 - y1 * (a / b);
    return d;
}

bool find_any_solution(int a, int b, int c, int &x0, int &y0, int &g) {
    g = gcd(abs(a), abs(b), x0, y0);
    if (c % g) {
        return false;
    }

    x0 *= c / g;
    y0 *= c / g;
    if (a < 0) x0 = -x0;
    if (b < 0) y0 = -y0;
    return true;
}

int better_less(int n, int v, bool t) {
    int val = 0;
    if(t)
        val = ceil(abs(n) / (v*1.0));
    else
        val = -(n / v);

    n = n + val*v;
    return n;
}

int32_t main()
{
    GO;
    int t;
    cin >> t;
    while(t--) {
        int x, y, p, q;
        cin >> x >> y >> p >> q;
        int INF = 2e18;
        int ans = INF;
        for(int v = 0; v < y; v++) {
            for(int e = 0; e < q; e++) {

                int c = (p + e - x - v);
                int a = (2*x + 2*y);
                int b = -(p + q);
                int n, h, g;
                if(find_any_solution(a, b, c, n, h, g)) {

                    /* some n and h such that we have time minimium*/
                    // cout << n << " " << h << endl;
                    // cout << "^^^^^^^^" << endl;
                    // cout << abs(b / g) << " " << abs(a / g) << endl;
                    // cout << "vvvvvvvv" << endl;
                    if(n < 0)
                        n = better_less(n, abs(b / g), 1);
                    else
                        n = better_less(n, abs(b / g), 0);
                    if(h < 0)
                        h = better_less(h, abs(a / g), 1);
                    else
                        h = better_less(h, abs(a / g), 0);

                    // cout << n << " " << h << endl;

                    int time1 = (2*x + 2*y)*n + x + v;
                    int time2 = (p + q)*h + p + e;
                    ans = min(ans, min(time1, time2));
                }
            }
        }
        if(ans >= INF)
            cout << "infinity" << endl;
        else
            cout << ans << endl;
    }
    return 0;
}


#include <iostream>
#include <queue>
#include <string>
#include <random>
using namespace std;

int maze[50][50];
bool used[50][50];
//"RDUL"
string moves = "RDUL";
int dx[4] = {0,1,-1,0};
int dy[4] = {1,0,0,-1};
int vals[50][50];
string fans = "";
long long fscore = 0;
const int inf = 1e9;

void dfs(int depth,int x,int y,string now,long long score){
    used[x][y] = true;
    score += (long long)vals[x][y];
    if (depth == 0){
        if (fscore < score){
            fscore = score;
            fans = now;
        }
        return;
    }
    int badx = -1,bady = -1;
    for (int k = 0; k < 4;k++){
        int nx = x + dx[k];
        int ny = y + dy[k];
        if (0 <= nx && nx < 50 && 0 <= ny && ny < 50
                && maze[nx][ny] == maze[x][y]){
                    if (!used[nx][ny]){
                        badx = nx;
                        bady = ny;
                    }
                    used[nx][ny] = true;
        }
    }
    vector<bool> can(4);
    vector<pair<int,int>> topoint(4);
    for (int k = 0; k < 4;k++){
        int nx = x + dx[k];
        int ny = y + dy[k];
        topoint[k] = {nx,ny};
        if (0 <= nx && nx < 50 && 0 <= ny && ny < 50
            && maze[nx][ny] != maze[x][y] && !used[nx][ny]){
                can[k] = true;
            }
    }
    bool candoit = false;
    for (int k = 0; k < 4;k++){
        if (can[k]) {
            candoit = true;
            dfs(depth-1,topoint[k].first,topoint[k].second,now+moves[k],score);
        }
    }
    if (candoit){
        if (fscore < score){
            fscore = score;
            fans = now;
        }
        return;
    }
    if (badx > 0){
        used[badx][bady] = false;
    }
    used[x][y] = false;

}

int main(){
    int sx,sy; // start point
    cin >> sx >> sy;
    for (int i = 0; i < 50;i++){
        for (int j = 0; j < 50;j++){
            cin >> maze[i][j];
        }
    }
    for (int i = 0; i < 50;i++){
        for (int j = 0; j < 50;j++){
            cin >> vals[i][j];
        }
    }
    for (int k = 0; k < 4;k++){
        int nx = sx + dx[k];
        int ny = sy + dy[k];
        if (0 <= nx && nx < 50 && 0 <= ny && ny < 50
                && maze[nx][ny] == maze[sx][sy]){
                    used[nx][ny] = true;
        }
    }
    dfs(inf,sx,sy,"",0);
    cout << fans << endl;

    return 0;
}

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;

#define dbl(k, x) fixed << setprecision(k) << (x)

template <typename _T>
inline void _DBG(const char *s, _T x) {
  cerr << s << " = " << x << "\n";
}
template <typename _T, typename... args>
void _DBG(const char *s, _T x, args... a) {
  while (*s != ',') cerr << *s++;
  cerr << " = " << x << ',';
  _DBG(s + 1, a...);
}

#define _upgrade                \
  ios_base::sync_with_stdio(0); \
  cin.tie(0);                   \
  cout.tie(0);
#define DBG(...) _DBG(#__VA_ARGS__, __VA_ARGS__)

// ********************** CODE ********************** //

const int nax = 107;
vector<int> G[nax];
vector<int> tin(nax);
set<pair<int, int>> SCC_edges_orientation;
int counter = 1;

void dfs(int u, int p) {
  tin[u] = counter;
  counter++;
  for (auto &v : G[u]) {
    if (v == p) {
      continue;
    }
    if (tin[v] == 0) {
      SCC_edges_orientation.emplace(u, v);
      dfs(v, u);
    } else if (tin[v] < tin[u]) {
      SCC_edges_orientation.emplace(u, v);
    }
  }
}

int main() {
  _upgrade;
  int n, m;
  cin >> n >> m;

  vector<pair<int, int>> edges(m);
  vector<string> direction(m);
  vector<int> reachable_cnt(n);

  for (auto &p : edges) {
    cin >> p.first >> p.second;
    p.first--;
    p.second--;
  }
  for (auto &v : reachable_cnt) {
    cin >> v;
  }

  for (int i = 0; i < m; i++) {
    int u = edges[i].first;
    int v = edges[i].second;
    if (reachable_cnt[u] < reachable_cnt[v]) {
      direction[i] = "<-";
    } else if (reachable_cnt[u] > reachable_cnt[v]) {
      direction[i] = "->";
    } else {
      G[u].push_back(v);
      G[v].push_back(u);
    }
  }

  for (int i = 0; i < n; i++) {
    if (tin[i] == 0) {
      dfs(i, -1);
    }
  }

  for (int i = 0; i < m; i++) {
    if (direction[i] != "") {
      continue;
    }
    if (SCC_edges_orientation.find(edges[i]) != SCC_edges_orientation.end()) {
      direction[i] = "->";
    } else {
      direction[i] = "<-";
    }
  }

  for (auto &dir : direction) {
    cout << dir << "\n";
  }
  return 0;
}


#include <bits/stdc++.h>

#pragma GCC optimize("O2")
#pragma GCC optimize("unroll-loops")

using namespace std;
#define ll long long
#define ull unsigned long long
#define rep(i,n,N) for(ll i=n;i<=N;++i)
#define asd(i,n,N) for(int i=n;i< N;++i)
#define rap(i,n,N) for(int i=n;i>=N;--i)
#define mp make_pair
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define fi first
#define se second
//#define ff fi.fi
//#define fs fi.se
#define sf se.fi
#define ss se.se
#define lc (id<<1)
#define rc ((id<<1)|1)
#define db(x) cout << ">>>> " << #x << " -> " << x << endl
#define mems(x,y) memset(x,y,sizeof x)
#define all(x) x.begin(),x.end()
#define rng() ((rand()<<16)|rand())
#define pii pair<int,int>
#define pll pair<ll,ll>
#define plll pair<ll,pll>
#define piii pair<int,pii>
#define piiii pair<pii,pii>
#define psi pair<string,int>
#define endl '\n'
const int MAX = 5e3+5;
const ll MAX2 = 11;
const ll MOD = 998244353;
const ll MOD2 = 2010405347;
const ll INF = 2e18;
const int dr[]={1,0,-1,0,1,1,-1,-1,0};
const int dc[]={0,1,0,-1,1,-1,1,-1,0};
const double pi = acos(-1);
const double EPS = 1e-9;
const int block = 555;

int n,m,a,b,k,y[MAX][MAX],z[MAX][MAX];
char x[MAX][MAX];
ll dp[MAX][MAX],pre[MAX*MAX];

ll f(int r,int c){
	if(r>n || c>m)return 0;
	if(r==n && c==m)return 1;
	ll &ret = dp[r][c];
	if(ret!=-1)return ret;
	ret = 0;
	if(x[r][c]){
		if(x[r][c]=='R')ret = f(r,c+1)*pre[y[r][c]];
		else if(x[r][c]=='D')ret = f(r+1,c)*pre[z[r][c]];
		else ret = f(r,c+1)*pre[y[r][c]] + f(r+1,c)*pre[z[r][c]];
	}
	else ret = (f(r,c+1)*pre[y[r][c]-1] + f(r+1,c)*pre[z[r][c]-1]) << 1;
	return ret%= MOD;
}

int main(){
// cout<<fixed<<setprecision(10);
// freopen("trip.in", "r", stdin);
// freopen("output.txt","w",stdout);
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin>>n>>m>>k;
    rep(i,1,k){
    	cin>>a>>b;
    	cin>>x[a][b];
	}
	k = n*m;
	pre[0] = 1;
	rep(i,1,k)pre[i] = pre[i-1]*3%MOD;
	rap(i,n,1)rap(j,m,1){
		y[i][j] = (!x[i][j]) + y[i+1][j];
		z[i][j] = (!x[i][j]) + z[i][j+1];
	}
	mems(dp,-1);
	ll ans = f(1,1);
	if(!x[n][m])ans = ans*3%MOD;
	cout<<ans<<endl;
    return 0;
}

# include <iostream>
# include <vector>

using namespace std;

const int kInf = 1 << 30;

bool flg;
int n, m;

int main() {
  scanf("%d %d", &n, &m);
  vector<int> dp(1 << n, kInf), cnt(n + 1);
  for (int i = 1; i <= n; i++) {
    cnt[i] |= (1 << (i - 1));
  }
  for (int i = 1, u, v; i <= m; i++) {
    scanf("%d %d", &u, &v);
    cnt[u] |= (1 << (v - 1)), cnt[v] |= (1 << (u - 1));
  }
  dp[0] = 0;
  for (int i = 1; i < 1 << n; i++) {
    flg = 1;
    for (int j = 1; j <= n; j++) {
      if (i >> (j - 1) & 1 && (cnt[j] & i) != i) {
        flg = 0;
      }
    }
    if (flg) {
      dp[i] = 1;
    } else {
      for (int j = i; j; j = (j - 1) & i) {
        dp[i] = min(dp[i], dp[j] + dp[i - j]);
      }
    }
  }
  printf("%d", dp[(1 << n) - 1]);
  return 0;
}


//-------All power is within you,you can do Anything and Everything.---------//

    #include <bits/stdc++.h>
    // #pragma GCC optimize("Ofast")
    using namespace std;
    //library

//*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ M $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*//

    #define F first
    #define S second
    #define pb push_back
    #define mkp make_pair
    #define int long long
    #define ld long double
    //scankar
    #define sz(x) (int)(x).size()
    #define all(x) x.begin(),x.end()
    #define rall(x) x.rbegin(),x.rend()
    #define fo(i,a,b) for(int i=a;i<b;i++)
    #define rfo(i,b,a) for(int i=b;i>=a;i--)
    #define mem( a, val ) memset(a, val, sizeof( a ) )
    #define deci( x ) cout<<fixed<<setprecision( x );
    #define bitcount( x ) __builtin_popcountll( x )
    #define endl "\n"

    #define XOX

    typedef vector<int> vi;
    typedef pair<int,int> pi;
    typedef map<int,int> mii;
    typedef map<int,bool> mib;
    typedef map<char,int> mci;
    typedef map<string,int> msi;

    const int INF = 1e18L + 5;
    const int MAX = 1500 + 2;
    const int MOD =  998244353;
    const long double PI  =3.141592653589793238463;
    //direction

//*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ D $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*//

    #define deb(x) cout<<#x<<" "<<x<<endl;
    //debugger

//*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ V $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*//

    int i,j,k,t,n,q,l,r,mid;

//*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ F $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*//

    vector<pi> v;
    int nn,mm,x,y,cnt,m;
    int a[MAX][MAX];
    void solve()
    {
        cin>>n>>m;
        cin>>nn>>mm;
        fo(i,0,nn)
        {
            cin>>x>>y;
            a[x][y]=1;
            v.pb({x,y});
        }
        fo(i,0,mm)
        {
            cin>>x>>y;
            a[x][y]=-1;
        }
        fo(i,0,nn)
        {
            x=v[i].F;
            y=v[i].S;
            fo(i,x+1,n+1)
            {
                if(a[i][y]==-1||a[i][y]>=1)break;
                a[i][y]++;
            }
        }
        fo(i,0,nn)
        {
            x=v[i].F;
            y=v[i].S;
            rfo(i,x-1,1)
            {
                if(a[i][y]==-1||a[i][y]>=2)break;
                a[i][y]++;
            }
        }
        fo(i,0,nn)
        {
            x=v[i].F;
            y=v[i].S;
            fo(i,y+1,m+1)
            {
                if(a[x][i]==-1||a[x][i]>=3)break;
                a[x][i]++;
            }
        }
        fo(i,0,nn)
        {
            x=v[i].F;
            y=v[i].S;
            rfo(i,y-1,1)
            {
                if(a[x][i]==-1||a[x][i]>=4)break;
                a[x][i]++;
            }
        }

        fo(i,1,n+1)
        {
            fo(j,1,m+1)
            {
                // cout<<a[i][j]<<" ";
                if(a[i][j]>0)cnt++;
            }
            // cout<<endl;
        }
        cout<<cnt<<endl;
    }

//*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*//
//                          THE GAME STARTS HERE                             //

    int32_t main()
    {

        // int start,stop=clock();
        // cout<<"time:"<<(stop-start)/double(CLOCKS_PER_SEC)*1000<<endl;
        ios_base::sync_with_stdio(0);
        cin.tie(NULL);
        cout.tie(NULL);

        // sc(t);while(t--)
        // cin>>t;while(t--)
            solve();

        return 0;
    }

#include<bits/stdc++.h>
using namespace std;

int main(){
    int h, w, n, m;
    cin >> h >> w >> n >> m;

    int che[h][w];
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            che[i][j] = 0;
        }
    }

    pair<int, int> light[n];
    for(int i = 0; i < n; i++){
        cin >> light[i].first >> light[i].second;
        light[i].first--;
        light[i].second--;
        che[light[i].first][light[i].second] = 2;
    }

    pair<int, int> wall;
    for(int i = 0; i < m; i++){
        cin >> wall.first >> wall.second;
        wall.first--;
        wall.second--;
        che[wall.first][wall.second] = -1;
    }

    for(int i = 0; i < n; i++){
        pair<int, int> s = light[i];
        for(int j = 0; j < 4; j++){
            if(j == 0){
                int t = 1;
                while(1){
                    if(s.first + t >= h){
                        break;
                    }

                    if(che[s.first + t][s.second] == -1 || che[s.first + t][s.second] == 2){
                        break;
                    }else if(che[s.first + t][s.second] == 0){
                        che[s.first + t][s.second] = 1;
                    }
                    t++;
                }
            }else if(j == 1){
                int t = 1;
                while(1){
                    if(s.first - t < 0){
                        break;
                    }

                    if(che[s.first - t][s.second] == -1 || che[s.first - t][s.second] == 2){
                        break;
                    }else if(che[s.first - t][s.second] == 0){
                        che[s.first - t][s.second] = 1;
                    }
                    t++;
                }
            }else if(j == 2){
                int t = 1;
                while(1){
                    if(s.second + t >= w){
                        break;
                    }

                    if(che[s.first][s.second + t] == -1 || che[s.first][s.second + t] == 2){
                        break;
                    }else if(che[s.first][s.second + t] == 0){
                        che[s.first][s.second + t] = 1;
                    }
                    t++;
                }
            }else{
                int t = 1;
                while(1){
                    if(s.second - t < 0){
                        break;
                    }

                    if(che[s.first][s.second - t] == -1 || che[s.first][s.second - t] == 2){
                        break;
                    }else if(che[s.first][s.second - t] == 0){
                        che[s.first][s.second - t] = 1;
                    }
                    t++;
                }
            }
        }
    }

    int ans = 0;
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            if(che[i][j] == 1 || che[i][j] == 2){
                ans++;
            }
        }
    }

    cout << ans << endl;
}


#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define ull unsigned ll
#define uint unsigned int
#define db double
#define pint pair<int,int>
#define mk make_pair
#define pb push_back
#define eb emplace_back
#define ins insert
#define fi first
#define se second
#define Rep(x,y,z) for(int x=(y);x<=(z);x++)
#define Red(x,y,z) for(int x=(y);x>=(z);x--)
using namespace std;
const int MAXN=1e5+5;
char buf[1<<12],*pp1=buf,*pp2=buf,nc;int ny;
inline char gc() {return pp1==pp2&&(pp2=(pp1=buf)+fread(buf,1,1<<12,stdin),pp1==pp2)?EOF:*pp1++;}
//inline char gc(){return getchar();}
inline int read(){
	int x=0;for(ny=1;nc=gc(),(nc<48||nc>57)&&nc!=EOF;)if(nc==45)ny=-1;if(nc<0)return nc;
	for(x=nc-48;nc=gc(),47<nc&&nc<58&&nc!=EOF;x=(x<<3)+(x<<1)+(nc^48));return x*ny;
}
int n;
inline int M(int x){return ((x-1)%n+n)%n+1;}
int main(){
//	freopen("std.in","r",stdin);
//	freopen("std.out","w",stdout);
	n=read();Rep(i,1,n)cout<<M(i<<1)<<' '<<M(i<<1|1)<<'\n';
	return 0;
}

#include <bits/stdc++.h>

#define pb push_back
#define int long long
#define ld long double
using namespace std;
const int M = 998244353;

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n;
    cin >> n;
    for (int x = 0; x < n; x++) {
        cout << 1 + (2 * x) % n << ' ' << 1 + (2 * x + 1) % n << '\n';
    }
}


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<map>
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const long long INF = 1LL << 60;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

int main(){
    long long n;
    cin>>n;
    if(n%2==0) cout<<"White"<<endl;
    else cout<<"Black"<<endl;
}

#include<bits/stdc++.h>
using namespace std;
int main(){int n;vector<int>a;cin>>n;for(int i=0,ai;i<n;i++)cin>>ai,a.push_back(ai);
if(set<int>(a.begin(),a.end()).size()==a.size())cout<<"Yes";else cout<<"No";}


//----AUTHOR:developer.eeshan----/
#include <bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
#define it(a, x) for (auto &a : x)
#define ll long long
#define ld long double
#define pb push_back
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define vpii vector<pii>
#define vs vector<string>
#define gi greater<int>
#define vc vector<char>
#define vvi vector<vi>
#define vvll vector<vll>
#define vvc vector<vc>
#define mii map<int, int>
#define pqb priority_queue<int>
#define pqs priority_queue<int, vi, greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define inf 1e18
#define ps(x, y) fixed << setprecision(y) << x
#define mk(arr, n, type) type *arr = new type[n];
#define w(x)  \
    int x;    \
    cin >> x; \
    while (x--)
#define deb(x) cout << #x << "=" << x << endl;
#define in(i, n) for (auto i = 0; i < n; i++)
#define all(a) begin(a), end(a)
#define rall(a) rbegin(a), rend(a)
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());  //random shuffler
ll fxp(ll a, ll b) {
    a %= mod;
    ll res = 1;
    while (b > 0) {
        if (b % 2 == 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b /= 2;
    }
    return res % mod;
}

inline ll minv(ll x) { return fxp(x, mod - 2); }
inline ll mmul(ll a, ll b) {
    if (a >= mod) a = a % mod;
    if (b >= mod) b = b % mod;
    if (a * b >= mod) return (a * b) % mod;
    return (a * b);
}
inline ll madd(ll a, ll b) {
    if (a >= mod) a = a % mod;
    if (b >= mod) b = b % mod;
    if (a + b >= mod) return (a + b) % mod;
    return (a + b);
}
inline ll msub(ll a, ll b) {
    if (a >= mod) a = a % mod;
    if (b >= mod) b = b % mod;
    return (((a - b) % mod + mod) % mod);
}
inline ll mdiv(ll a, ll bb) {
    if (a >= mod) a = a % mod;
    ll b = minv(bb);
    if (b >= mod) b = b % mod;
    if (a * b >= mod) return (a * b) % mod;
    return (a * b);
}

void c_p_c() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
#endif
}

const int mXn = 2e5 + 5;
int n, m, h[mXn], w[mXn], o[mXn], e[mXn];

void solve() {
    cin >> n >> m;
    in(i, n)cin >> h[i];
    in(i, m)cin >> w[i];
    sort(h, h + n);
    //in(i, n)cout << h[i] << ' ';
    //cout << endl;
    o[1] = h[1] - h[0];
    for (int i = 3; i < n; i += 2) o[i] = o[i - 2] + (h[i] - h[i - 1]);
    for (int i = 2; i < n; i += 2) e[i] = e[i - 2] + (h[i] - h[i - 1]);
    ll ans = 1e15;
    in(i, m) {
        int pos = upper_bound(h, h + n, w[i]) - h - 1;
        //pos=-1, pos=n-1
        //cout << "for " << w[i] << " pos is " << pos;
        ll cans = 0;
        if (pos == -1) {
            cans += e[n - 1] + (h[0] - w[i]);
        } else if (pos == n - 1) {
            cans += o[n - 2] + (w[i] - h[n - 1]);
        } else {
            if (pos % 2 == 1)
                pos++;
            cans += abs(w[i] - h[pos]) + o[pos - 1] + (e[n - 1] - e[pos]);
        }
        //cout << " cans is: " << cans << endl;
        ans = min(ans, cans);
    }
    cout << ans;
}

int main(int argc, char const *argv[]) {
    c_p_c();
    solve();
    return 0;
}

// E - Transformable Teacher
#include <bits/stdc++.h>
using namespace std;

int main(){
	int n, m; cin>>n>>m;
	vector<int> H(n), W(m), evn(1), odd(1); // 偶・奇数番目の累積和
	for(int& x:H) cin>>x;
	for(int& x:W) cin>>x;
	sort(H.begin(), H.end());

	for(int i=0; i<n-1; ++i){
		int d = H[i+1] - H[i];
		if(i%2) odd.push_back(odd.back() + d);
		else evn.push_back(evn.back() + d);
	}

	int64_t ans = LLONG_MAX;
	for(int w:W){
		int r = upper_bound(H.begin(), H.end(), w) - H.begin();
		int i = r / 2;
		r -= r%2;
		ans = min(ans, (int64_t)evn[i] + abs(w - H[r]) + odd.back() - odd[i]);
	}
	cout<< ans <<endl;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  int L;
  cin >> L;
  long long over=1;
  vector<int> ok(10);

  for(int i=1; i<=11; i++) {
    over *= (L-i);
    for(int k=2; k<=11; k++) {
      if( (over%k) == 0 && ok.at(k-2) == 0) {
        over /= k;
        ok.at(k-2) = 1;
      }
    }
  }
  cout << over << endl;
}

#ifdef DEBUG_BUILD
# define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
#ifdef DEBUG_BUILD
# include "debugger.hpp"
#else
# define debug(...)
# define debugdo(...)
#endif
using namespace std;
using ll = long long;
using ld = long double;
using pll = std::pair<ll, ll>;
template <class T> using vec = std::vector<T>;
template <class T> using vec2 = std::vector<vec<T>>;
template <class T> using vec3 = std::vector<vec2<T>>;
#define rep(i, N) for (ll i = 0; i < (N); i++)
#define rrep(i, N) for (ll i = (N) - 1; i >= 0; i--)
#define range(i, A, B) for (ll i = (A); i < (B); i++)
constexpr int MOD = 1000000007;
constexpr ll INFL = std::numeric_limits<ll>::max();
template <class T> bool chmax(T &a, const T b) { if (a < b) { a = b; return true; } return false; }
template <class T> bool chmin(T &a, const T b) { if (a > b) { a = b; return true; } return false; }

void Main() {
    string S;
    cin >> S;
    reverse(S.begin(), S.end());
    for (auto& c : S) {
        switch(c) {
        case '6':
            c = '9';
            break;
        case '9':
            c = '6';
            break;
        }
    }
    cout << S << endl;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    std::cout << std::fixed << std::setprecision(10);
    Main();
    std::cout << std::flush;
    std::cerr << "--end--" << std::flush;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
#define FOR(i, n) for(int (i)=0; (i)<(n); (i)++)
#define FOR1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FORI(i, n) for(int (i)=n-1; (i)>=0; (i)--)
template<class T, class U> void umin(T& x, const U& y){ x = min(x, (T)y);}
template<class T, class U> void umax(T& x, const U& y){ x = max(x, (T)y);}
template<class T, class U> void init(vector<T> &v, U x, size_t n) { v=vector<T>(n, (T)x); }
template<class T, class U, typename... W> void init(vector<T> &v, U x, size_t n, W... m) { v=vector<T>(n);  for(auto& a : v) init(a, x, m...); }

double x, y, r;
bool dist(double x1, double y1, double x2, double y2){
    ll xx1 = round(x1 * 1e4);
    ll yy1 = round(y1 * 1e4);
    ll xx2 = round(x2 * 1e4);
    ll yy2 = round(y2 * 1e4);
    ll r2 = round(r * 1e4);
    return (xx1-xx2)*(xx1-xx2) + (yy1-yy2)*(yy1-yy2) <= r2*r2;
}

const int inf = 1e9;
int bs(int x2, int dir){
    int y2 = ceil(y);
    if (dir == -1)
        y2 = floor(y);
    if (!dist(x2, y2, x, y)) return inf;

    int a = 0, b = r+1, ret = 0;
    while(a <= b){
        int c = (a+b)/2;
        if (dist(x2, y2+dir*c, x, y)){
            ret = c;
            a = c+1;
        }
        else{
            b = c-1;
        }
    }
    return y2 + dir * ret;
}

int main(int argc, char** argv) {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << setprecision(15);
    if (argc == 2 && atoi(argv[1]) == 123456789) freopen("d:\\code\\cpp\\contests\\stdin", "r", stdin);
    cin >> x >> y >> r;
    ll ans = 0;
    for(double dx = -r-10; dx <= r+10; dx++){
        int x2 = floor(x + dx);
        int ymax = bs(x2, 1);
        int ymin = bs(x2, -1);
        if (ymax != inf && ymin != inf)
            ans += ymax - ymin + 1;
        else if (ymax != inf)
            ans += ymax - (int)ceil(y) + 1;
        else if (ymin != inf)
            ans += (int)floor(y) - ymin + 1;
    }
    cout << ans << endl;

    if (argc == 2 && atoi(argv[1]) == 123456789) cout << clock()*1.0/CLOCKS_PER_SEC << " sec\n";
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using s64 = signed long long;
using u64 = unsigned long long;
using f128 = long double;

s64 GetCeilS64(s64 fixed, s64 digit)
{
    if(fixed % digit == 0)
    {
        return fixed;
    }

    if(fixed > 0)
    {
        return ((fixed / digit) + 1) * digit;
    }
    else
    {
        return (fixed / digit) * digit;
    }
}
s64 GetFloorS64(s64 fixed, s64 digit)
{
    if(fixed % digit == 0)
    {
        return fixed;
    }

    if(fixed > 0)
    {
        return (fixed / digit) * digit;
    }
    else
    {
        return ((fixed / digit) - 1) * digit;
    }
}

int main()
{
    f128 x, y, r;
    cin >> x >> y >> r;

    s64 digit = pow(10, 4);
    s64 xInt = llround(x * digit);
    s64 yInt = llround(y * digit);
    s64 rInt = llround(r * digit);

    u64 countInt = 0;
    s64 startX = GetCeilS64(xInt - rInt, digit);
    s64 endX = GetFloorS64(xInt + rInt, digit);

    for(s64 i = startX; i <= endX; i += digit)
    {
        s64 rIntSq = rInt*rInt;
        s64 xIntSq = (i-xInt) * (i-xInt);
        s64 yIntSq = rIntSq - xIntSq;
        s64 p = sqrtl(yIntSq);
        s64 startY = GetCeilS64(yInt - p, digit);
        s64 endY = GetFloorS64(yInt + p, digit);
        if(startY > endY)
        {
            continue;
        }
        u64 subCount = endY/digit - startY/digit + 1;
        countInt += subCount;
    }

    cout << countInt << endl;

    return 0;
}


#include <bits/stdc++.h>
#define REP(i, nn ) for(int i = 0 ; i < (int) nn; i++)
#define REPS(i, ss, nn ) for(int i = ss ; i < (int) nn; i++)
#define REV(i, ss, nn ) for(int i = ss ; i >= nn; i--)
#define deb(x) std::cout << #x << " " << x << endl;
#define debl(x) std::cout << #x << " " << x << " ";
#define all(x) x.begin(), x.end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
namespace std{
    template<class Fun>
    class y_combinator_result{
        Fun fun_;
        public:
            template<class T>
            explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)){}
            template<class ...Args>
            decltype(auto) operator()(Args&&...args){
                return fun_(std::ref(*this), std::forward<Args>(args)...);
            }
    };
    template<class Fun>
    decltype(auto) y_combinator(Fun && fun){
        return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
    }
};
template<typename T>
bool umax(T& a, T b){
    bool ret = a < b;
    if(ret) a = b;
    return ret;
}
template<typename T>
bool umin(T& a, T b){
    bool ret = a > b;
    if(ret) a = b;
    return ret;
}
struct edge{
    int to; ll cost;
    int from;
    edge(){ edge(0,0);}
    edge(int to_, ll cost_) : to(to_), cost(cost_){}
    edge(int to_, int from_, ll cost_) : to(to_), cost(cost_), from(from_){}
};

template<typename... T>
void read(T& ... a){
    ((cin >> a),...);
}

template<typename... T>
void write(T... a){
    ((cout << a),...);
}

template<typename T>
vector<T> read_array(int sz){
    vector<T> ret(sz);
    for(auto & x : ret) cin >> x;
    return ret;
}

void solve(){
    int n;
    read(n);
    map<int, int> mp;
    REP(i, n){
        int a;
        read(a);
        mp[a]++;
    }
    vi b(n), c(n);
    REP(i, n) read(b[i]);
    REP(i, n) read(c[i]);
    ll ans = 0;
    REP(i, n){
        int x = b[c[i] - 1];
        if(mp.find(x) != mp.end()){
            ans += mp[x];
        }
    }
    write(ans);
}

int main()
{
    //making data IO Fast
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
    /****************************/
    int T = 1;
    // cin >> T;
    while(T--)
        solve();
    return 0;
}

#include <bits/stdc++.h>
#define fo(i, k, n) for (ll i = k; i < n; i++)
#define rfo(i, k, n) for (ll i = k; i >= n  ; i--)
#define ll long long
#define ld long double
#define que queue
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define vl vector<ll>
#define gcd(m,n) __gcd( m,  n)
#define sq(x)   (x*x)
#define rev(v)  reverse(v.begin(),v.end())
#define srt(v)  sort(v.begin(),v.end())
#define grtsrt(v) sort(v.begin(),v.end(),greater<int>())
#define mnv(v)     *min_element(v.begin(),v.end())
#define mxv(v)    *max_element(v.begin(),v.end())
#define all(v)    v.begin(),v.end()
#define toInteger(s) stoll(s)
#define toString(num) to_string(num)

using namespace std;
ll MOD = 1e9 + 7;
//--------------------------------------------functions-------------------------------------------------//

ll power(ll a,ll b){ll result=1;while(b>0){if(b%2 == 1){result *= a;} a *= a;b /= 2;}return result;}
ll countSetBits(ll x){ll Count=0;while(x>0){if(x&1) Count++;x=x>>1;}return Count;}
bool isPerfectSquare(ll n){ll sr = sqrt(n);if (sr * sr == n)return true;else return false;}
ll mod(ll x,ll M){return ((x%M + M)%M);}
ll mul(ll a, ll b,ll M){return mod(mod(a,M)*mod(b,M),M);}
ll powerM(ll a,ll b,ll M){
    ll res=1ll;
    while(b){
        if(b%2ll==1ll){
            res=mul(a,res,M);
        }
        a=mul(a,a,M);b/=2ll;
    }
    return res;
}
int log22(long long x)
{
    return 64 - __builtin_clzll(x) - 1;
}

//--------------------------------------------SieveOfEratosthenes-------------------------------------------------//
//mem will have true if its prime.
void SieveOfEratosthenes( vector<bool>&mem)
{ ll n = 1e6 +1;

    bool prime[n + 1];
    memset(prime, true, sizeof(prime));

    for (int p = 2; p * p <= n; p++)
    {

        if (prime[p] == true)
        {
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }

     fo(i,2,n)
     if(prime[i])mem[i]=true;

}

//--------------------------------------------solve-------------------------------------------------//

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
 // freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);

  int n;
  cin>>n;

  vector<int>v(n);
  fo(i,0,n)
  cin>>v[i];
 ll ans = 0;
  fo(i,0,n)
  {
    if(v[i]>10)
        ans += v[i]-10;
  }
 cout<<ans;

  return 0;
}


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <iostream>
#include <cassert>
#include <cmath>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>

using namespace std;

#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define li long long
#define pii pair<int, int>
#define vi vector<int>
#define li long long

#define forn(i, n) for (int i = 0; i < (int)n; i++)
#define fore(i, b, e) for (int i = (int)b; i <= (int)e; i++)

const int MAXN = 2005;
const int INF = 2e9;

vector<pii> edges[MAXN];
int dist[MAXN];

int main() {
	int n, m;
	scanf("%d%d", &n, &m);
	forn(i, m) {
		int x, y, w;
		scanf("%d%d%d", &x, &y, &w);
		edges[x].pb({y, w});
	}
	fore(start, 1, n) {
		set<pii> order;
		fore(u, 1, n) {
			dist[u] = INF;
		}
		dist[start] = 0;
		int ans = INF;
		order.insert({0, start});
		while (!order.empty()) {
			pii f = *order.begin();
			order.erase(order.begin());
			int v = f.se;
			if (dist[v] != f.fi) {
				continue;
			}
			for (pii e : edges[v]) {
				int u = e.fi;
				if (dist[u] > dist[v] + e.se) {
					dist[u] = dist[v] + e.se;
					order.insert({dist[u], u});
				}
				if (u == start) {
					ans = min(ans, dist[v] + e.se);
				}
			}
		}
		if (ans == INF) {
			ans = -1;
		}
		printf("%d\n", ans);
	}
}

#include <bits/stdc++.h>

using namespace std;

#define ar array
#define ll long long

const int MAX_N = 1e5 + 1;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll LINF = 1e18;

ll helper(ll a){
  vector<int> vec(10,0);
  while(a){
    vec[a%10]++;
    a/=10;
  }
  ll v1=0,v2=0;
  for(int i=0;i<10;i++){
    for(int j=0;j<vec[i];j++)v2=v2*10+i;
  }
  for(int i=9;i>=0;i--){
    for(int j=0;j<vec[i];j++)v1=v1*10+i;
  }
  return v1-v2;
}

void solve() {

  ll n,k;
  cin>>n>>k;
  while(k){
    ll tmp=helper(n);
    if(tmp==n){
      cout<<tmp<<endl;
      return;
    }
    n=tmp;
    k--;
  }
  cout<<n<<endl;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  //freopen("input.txt", "r", stdin);
  //freopen("output.txt", "w", stdout);

  int tc = 1;
  //cin >> tc;
  for (int t = 1; t <= tc; t++) {
    solve();
  }
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
//g++ c.cpp
//./a.out
//oj d https://atcoder.jp/contests/abc205/tasks/abc205_c
//oj t

signed main(){
    int a, b, c;
    cin >> a >> b >> c;
    if(c%2==0){
        if(abs(a)>abs(b)){
            cout << ">" << endl;
            return 0;
        }
        else if(abs(a)<abs(b)){
            cout << "<" << endl;
            return 0;
        }
        else if (abs(a) == abs(b))
        {
            cout << "=" << endl;
            return 0;
        }
    }
    else if(c%2==1){
        if(a>b)
        {
            cout << ">" << endl;
            return 0;
        }
        else if(a<b){
            cout << "<" << endl;
            return 0;
        }
      else if(a==b){
                    cout << "=" << endl;
            return 0;
      }
    }
}


#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max() / 32 * 15 + 208;

int main() {
    ll a, b, k;
    cin >> a >> b >> k;
    const int maxn = 60;
    ll C[maxn + 1][maxn + 1];
    C[0][0] = 1;
    for (int n = 1; n <= maxn; ++n) {
        C[n][0] = C[n][n] = 1;
        for (int m = 1; m < n; ++m)
            C[n][m] = C[n - 1][m - 1] + C[n - 1][m];
    }
    k--;
    string ans;
    while(a || b){
        if(!b) {
            ans += 'a';
            a--;
        }else if(!a){
            ans += 'b';
            b--;
        }else if(k < C[a+b-1][b]){
            ans += 'a';
            a--;
        }else {
            ans += 'b';
            k -= C[a+b-1][b];
            b--;
        }
    }
    cout << ans << "\n";
    return 0;
}

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

void _cin(){} template <class Head, class... Tail> void _cin(Head&& head, Tail&&... tail){ cin >> head; _cin(forward<Tail>(tail)...); }
template<class T> void _cout(T &&x){ cout << x << "\n"; } template <class Head, class... Tail> void _cout(Head&& head, Tail&&... tail){ cout << head << " "; _cout(forward<Tail>(tail)...); }
template<typename S, typename T> ostream& operator<<(ostream &os, const pair<S, T> &p){ cout << "[" << p.first << ", " << p.second << "]"; return os; }

#define Sq(x) (x)*(x)
#define For(i, n) for(int i = 0; i < (n); i ++)
#define For1(i, n) for(int i = 1; i <= (n); i ++)
#define Rof(i, n) for(int i = (n)-1; i >= 0; i --)
#define Rep(n) For(_, n)
#define Range(c) c.begin(), c.end()
#define RevRange(c) c.rbegin(), c.rend()
#define Contains(c, x) (find(Range(c), x) != c.end())
#define Search(rb, re, x) distance(rb, find(rb, re, x))
#define Sort(a) sort(Range(a))
#define DeSort(a) sort(RevRange(a))
#define Reverse(c) reverse(Range(c))
#define Unique(a) a.erase(unique(Range(a)), a.end())
#define Cusum(T, xs, sxs) vector<T> sxs(xs.size()+1); For(i, (int)xs.size()) sxs[i+1] = sxs[i] + xs[i]
#define Cin(T, ...) T __VA_ARGS__; _cin(__VA_ARGS__)
#define Cins(T, n, xs) vector<T> xs(n); For(i, n) cin >> xs[i]
#define Cins2(T, n, xs, ys) vector<T> xs(n), ys(n); For(i, n) cin >> xs[i] >> ys[i]
#define Cins3(T, n, xs, ys, zs) vector<T> xs(n), ys(n), zs(n); For(i, n) cin >> xs[i] >> ys[i] >> zs[i]
#define Cinss(T, m, n, xs) vector<vector<T>> xs(m, vector<T>(n)); For(i, m) For(j, n) cin >> xs[i][j]
#define Cinm(T, n, map) unordered_map<T, int> map; Rep(n){ Cin(T, x); map[x] ++; }
#define Cout(...) _cout(__VA_ARGS__)
#define Couts(xs) { for(const auto &e : xs) cout << e << " "; cout << "\n"; }
#define Coutss(xs) { For(i, xs.size()) Couts(xs[i]); }
#define Coutyn(cond) Cout((cond) ? "yes" : "no")
#define CoutYn(cond) Cout((cond) ? "Yes" : "No")
#define CoutYN(cond) Cout((cond) ? "YES" : "NO")
#define Return(expr) { Cout(expr); return 0; }
#define vc vector
#define Vc2(T, m, n, xs) vc<vc<T>> xs(m, vc<T>(n))
#define Mini(a, x) a = min(a, x)
#define Maxi(a, x) a = max(a, x)

// constexpr int MOD = 1e9+7;
// constexpr long double tau = 6.28318530717958647692;

int main(void){
    Cin(int, a, b);
    int n = a+b;
    Vc2(ll, n+1, n+1, c);
    c[0][0] = 1;
    For1(i, n) For1(j, n) c[i][j] = c[i-1][j-1] + c[i-1][j];

    Cin(ll, k);
    string ans = "";
    ll skipped = 0;
    Rep(n){
        if(skipped + c[a+b][a] < k){
            skipped += c[a+b][a];
            ans += 'b';
            b --;
        }
        else{
            ans += 'a';
            a --;
        }
    }
    Cout(ans);
}


#include <bits/stdc++.h>
#define i64 long long
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define per(i, a, b) for (int i = (b) - 1; i >= (a); --i)
using namespace std;

const int M = 3;
struct mint {
	int x; mint(int x) : x(x) {}
	friend mint operator + (const mint &a, const mint b)
	 {const int x = a.x + b.x; return mint(x >= M ? x - M : x);}
	friend mint operator - (const mint &a, const mint b)
	 {const int x = a.x - b.x; return mint(x < 0 ? x + M : x);}
	friend mint operator * (const mint &a, const mint b)
	 {return mint(1ll * a.x * b.x % M);}
};
int Pw(int a, int x = M - 2, int res = 1) {
	for (; x; x >>= 1, a = (mint(a) * a).x)
	 {if (x & 1) {res = (mint(res) * a).x;}}
	return res;
}

const int N = 4e5;
int n; string s;
struct par {
	int p, c;
	par(int x) : p(x), c(0) {while (!(p % M)) {p /= M, ++c;}}
};

int main() {
	// freopen("c.in", "r", stdin); //
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n >> s;
	int res = 0; par f = 1;
	rep(i, 0, n) {
		int x = s[i] == 'B' ? 0 : (s[i] == 'W' ? 1 : 2);
		// cout << f.p << ' ' << f.c << '\n'; //
		if (!f.c) {res = (res + mint(f.p) * x).x;}
		if (i == n - 1) {break;}
		par m = n - 1 - i, d = i + 1;
		f.p = (mint(f.p) * m.p * Pw(d.p)).x;
		f.c = f.c + m.c - d.c;
	}
	if (!(n & 1)) {res = (mint(0) - res).x;}
	cout << (res == 0 ? 'B' : (res == 1 ? 'W' : 'R')) << '\n';
	return 0;
}

/* 📌https://www.cnblogs.com/George1123/p/tips.html */

#include <iostream>
#include <vector>
#define mod 998244353

using namespace std;

int n, k;

vector <vector <int> > a;
vector <int> hgroups;
vector <int> vgroups;
vector <int> rep;
vector <int> sizes;
vector <long long> fact;

bool compc(int x, int y) {
	for (int i = 0; i < n; i++) {
		if (a[i][x] + a[i][y] > k) return false;
	}

	return true;
}

bool compr(int x, int y) {
	for (int i = 0; i < n; i++) {
		if (a[x][i] + a[y][i] > k) return false;
	}

	return true;
}

int find(int x) {
	while (x != rep[x]) x = rep[x];
	return x;
}

bool same(int a, int b) {
	return find(a) == find(b);
}

void unite(int a, int b) {
	a = find(a);
	b = find(b);
	if (sizes[a] < sizes[b]) swap(a, b);
	sizes[a] += sizes[b];
	rep[b] = a;
}

int main() {
	cin >> n >> k;
	int temp;
	a.resize(n);
	long long res = 1;
	for (int i = 0; i < n; i++) {
		for (int i = 0; i < n; i++) {
			cin >> temp;
			a[i].push_back(temp);
		}
	}

	rep.resize(n);
	sizes.resize(n);
	for (int i = 0; i < n; i++) {
		rep[i] = i;
		sizes[i] = 1;
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < i; j++) {
			if (compc(i, j) && !same(i, j)) unite(i, j);
		}
	}

	fact.resize(n + 1);
	fact[0] = 1;
	for (int i = 1; i <= n; i++) {
		fact[i] = fact[i - 1] * i;
		fact[i] %= mod;
	}

	for (int i = 0; i < n; i++) {
		if (rep[i] == i) {
			res *= fact[sizes[i]];
			res %= mod;
		}
	}

	rep.clear();
	sizes.clear();

	rep.resize(n);
	sizes.resize(n);
	for (int i = 0; i < n; i++) {
		rep[i] = i;
		sizes[i] = 1;
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < i; j++) {
			if (compr(i, j) && !same(i, j)) unite(i, j);
		}
	}

	for (int i = 0; i < n; i++) {
		if (rep[i] == i) {
			res *= fact[sizes[i]];
			res %= mod;
		}
	}

	cout << res << endl;

	return 0;
}


// Author:   old_school
// Created:  02.01.2021 17:30:15

#include<bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
using namespace std;
#define lld               long long int
#define ld                long double
#define pb                push_back
#define ppb               pop_back
#define mp                make_pair
#define F                 first
#define S                 second
#define nl                '\n'
#define all(c)            (c).begin(),(c).end()
#define rall(c)           (c).rbegin(),(c).rend()
#define sz(c)             (c).size()
#define tr(x,a)           for(auto &a : x)
#define psnt(x,a)         (x).find(a)!=(x).end()
#define vpsnt(x,a)        find(all(x),a)!=(x).end()
#define MOD               1000000007
#define tod               1
#define pi                3.1415926536
#define itr(i,a,b)        for(lld i=a;i<=b;i++)
#define itrn(i,a,b)       for(lld i=a;i>=b;i--)
#define iot(n)            for(lld i=0;i<n;i++)
#define pls(n,arr)        lld arr[n]; iot(n)  cin>>arr[i];
#define bye               fflush(stdout)

typedef pair<lld,lld>     pii;
typedef pair<string,lld>  psi;

template <typename T>
bool mycomp(T x,T y){
   return (x==y);  //give your condition here
}
bool paircomp(const pair<lld,lld> &x,const pair<lld,lld> &y){
return x.second<y.second;
}

void solve(){
   lld n; cin>>n;
   lld a[n],b[n];
   iot(n) cin>>a[i]>>b[i];
   lld ans=0;
   iot(n){
   	itr(j,i+1,n-1){

   		ld x2=1.00*abs(a[j]-a[i]);
   		ld y2=1.00*abs(b[j]-b[i]);
   		ld slope=1.00*y2/x2;
   		ld asf=1.00-slope;
   		ld bsf=1.00+slope;
   		if(asf>=0.00&&bsf>=0.00)  ans++;
   	//	if(aa>=0&&bb>=0) ans++;
   	}

   }cout<<ans;
}
int main(){
       ios_base::sync_with_stdio(false);
             cin.tie(0);
            cout.tie(0);
      lld t=1;// cin>>t;
      while(t--){
            solve();
            cout<<endl;
      }
}

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
using namespace std;
using ll = long long;
const int INF = 1000000000;
const int MOD = 1000000007;
const ll llINF = 1000000000000000000;

// #include <atcoder/all>
// using namespace atcoder;
// #include <boost/multiprecision/cpp_int.hpp>
// using lll = boost::multiprecision::cpp_int;

void solve() {
  int n;
  cin >> n;
  vector<ll> a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
  }
  ll ans = 0;
  for (int i = 0; i < n; ++i) {
    ll mini = llINF;
    for (int j = i; j < n; ++j) {
      mini = min(mini, a[j]);
      ans = max(ans, (ll(j) - ll(i) + 1) * mini);
    }
  }
  cout << ans << endl;
}

int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);
  std::cout << std::fixed << std::setprecision(15);
  solve();
  return 0;
}


#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int N = 3e5 + 7;
int32_t main(){
    IOS;
    int t;
    t=1;
    while(t--){
        int x,y;
        cin >> x >> y;
        int p = abs(x-y);
        if(p>=3) cout << "No" ;
        else cout << "Yes";

        cout << endl;
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main(){
  vector<int> a(4);
  for(int i=0;i<4;i++){
    cin>>a[i];
  }
  sort(a.begin(),a.end());
  cout<<a[0]<<endl;
  return 0;
}


#include <bits/stdc++.h>
#include <array>
#include <cstdlib>
using namespace std;

int main() {
  vector<int> a(3);
  for(int i =0; i < 3; i++){
    cin >> a[i];
  }
  sort(a.begin(), a.end());
  if(a[2]-a[1] == a[1]-a[0]){
    cout << "Yes" << endl;
  }
  else cout << "No" << endl;

}

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int v,t,s,d;
    cin>>v>>t>>s>>d;
    if(v*t<=d&&s*v>=d)
    {
        cout<<"No";
    }
    else cout<<"Yes";
}


#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int BUF = 100005;

class ChildData {
public:
    int subtreeNode;
    int fstTake, scdTake;

    ChildData(){}
    ChildData(int sb, int f, int scd):
        subtreeNode(sb), fstTake(f), scdTake(scd) {}

    bool operator< (const ChildData &opp) const {
        return fstTake - scdTake < opp.fstTake - opp.scdTake;
    }
};

int nNode;
vector<int> adj[BUF];

void read() {
    for (int i = 0; i < BUF; ++i) adj[i].clear();

    cin >> nNode;
    for (int i = 1; i < nNode; ++i) {
        int pre;
        cin >> pre;
        --pre;
        adj[pre].push_back(i);
        adj[i].push_back(pre);
    }
}

ChildData rec(int cur, int pre) {
    ChildData ret(0, 0, 0);

    vector<ChildData> childResult;
    vector<ChildData> evenResult;

    for (int i = 0; i < adj[cur].size(); ++i) {
        int nex = adj[cur][i];
        if (nex == pre) continue;

        ChildData candi = rec(nex, cur);
        if (candi.subtreeNode % 2 == 0) {
            if (candi.fstTake - candi.scdTake < 0) {
                ret.subtreeNode += candi.subtreeNode;
                ret.fstTake += candi.fstTake;
                ret.scdTake += candi.scdTake;
            } else {
                evenResult.push_back(candi);
            }
        } else {
            childResult.push_back(candi);
        }
    }

    sort(childResult.begin(), childResult.end());

    for (int i = 0; i < childResult.size(); ++i) {
        ChildData &r = childResult[i];
        if (i % 2 == 0) {
            ret.subtreeNode += r.subtreeNode;
            ret.fstTake += r.fstTake;
            ret.scdTake += r.scdTake;
        } else {
            ret.subtreeNode += r.subtreeNode;
            ret.fstTake += r.scdTake;
            ret.scdTake += r.fstTake;
        }
    }
    for (int i = 0; i < evenResult.size(); ++i) {
        ChildData &r = evenResult[i];
        if (ret.subtreeNode % 2 == 0) {
            ret.subtreeNode += r.subtreeNode;
            ret.fstTake += r.fstTake;
            ret.scdTake += r.scdTake;
        } else {
            ret.subtreeNode += r.subtreeNode;
            ret.fstTake += r.scdTake;
            ret.scdTake += r.fstTake;
        }
    }

    ++ret.subtreeNode;
    ++ret.fstTake;

    return ret;
}

void work() {
    cout << rec(0, -1).fstTake << endl;
}

int main() {
    read();
    work();
    return 0;
}

#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
//#include<atcoder/all>
//using namespace atcoder;
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

int P[100001];
int sei[100001], fu[100001], kisuu[100001], kazu[100001], kazu2[100001];
void sort_ganbare(int N, int A[]) {
	if (N < (1 << 12)) {
		sort(A, A + N);
		return;
	}
	const int b = 9;
	int tmp[100001];
	int kazu[1 << b] = {}, kazu2[1 << b] = {};
	rep(i, N) kazu[A[i] & ((1 << b) - 1)]++;
	rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
	for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] & ((1 << b) - 1)]] = A[i];
	rep(i, N) kazu2[tmp[i] >> b & ((1 << b) - 1)]++;
	rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
	for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> b & ((1 << b) - 1)]] = tmp[i];
}
const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += 72 - dig >> 3;
	return tmp;
}

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

	int N = getint();
	rep1(i, N - 1) {
		kazu[(P[i + 1] = getint())]++;
	}
	rep(i, N) kazu2[i + 1] = (kazu[i + 1] += kazu[i]);

	for (int i = N; i >= 2; i--) {
		int ret = sei[i] - 1;

		auto ki = kisuu + kazu[i - 1];
		int sz = kazu2[i - 1] - kazu[i - 1];
		sort_ganbare(sz, ki);

		if (sz & 1) {
			ret -= fu[i];
			rep(j, sz) {
				if (j & 1) ret -= ki[j] - (1 << 17);
				else ret += ki[j] - (1 << 17);
			}
		}
		else {
			ret += fu[i];
			rep(j, sz) {
				if (j & 1) ret += ki[j] - (1 << 17);
				else ret -= ki[j] - (1 << 17);
			}
		}

		if (ret & 1) {
			kisuu[kazu2[P[i] - 1]++] = ret + (1 << 17);
		}
		else {
			if (ret >= 0) sei[P[i]] += ret;
			else fu[P[i]] += ret;
		}
	}

	int ret = sei[1] - 1;

	auto ki = kisuu + kazu[0];
	int sz = kazu2[0] - kazu[0];
	sort_ganbare(sz, ki);

	if (sz & 1) {
		ret -= fu[1];
		rep(j, sz) {
			if (j & 1) ret -= ki[j] - (1 << 17);
			else ret += ki[j] - (1 << 17);
		}
	}
	else {
		ret += fu[1];
		rep(j, sz) {
			if (j & 1) ret += ki[j] - (1 << 17);
			else ret -= ki[j] - (1 << 17);
		}
	}

	co((N - ret) / 2);

	Would you please return 0;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int,int> pii;
int h,w,dis[4000500],sx,sy,tx,ty,vis[4000500];
char sp[2005][2005];
priority_queue<pii > q;
vector<int> gg[30];

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

int dp(int i,int j){return i*w+j;}

int main()
{
	scanf("%d%d",&h,&w);
	for(int i=0;i<h;i++)
		scanf("%s",sp[i]);
	for(int i=0;i<h;i++)
		for(int j=0;j<w;j++)
		{
			if(sp[i][j]=='S') sx=i,sy=j;
			if(sp[i][j]=='G') tx=i,ty=j;
			if(sp[i][j]>='a' && sp[i][j]<='z')
				gg[sp[i][j]-'a'].push_back(i*w+j);
		}
	memset(dis,-1,sizeof(dis));
	dis[sx*w+sy]=0;
	q.push(make_pair(0,sx*w+sy));
	while(!q.empty())
	{
		int now=q.top().second;q.pop();
		if(vis[now]) continue;vis[now]=1;
		if(now<h*w){
			int x=now/w,y=now%w;
			for(int a=0;a<4;a++)
			{
				int nx=x+dx[a],ny=y+dy[a];
				if(nx>=0 && nx<h && ny>=0 && ny<w && sp[nx][ny]!='#' && (dis[nx*w+ny]==-1 || dis[nx*w+ny]>dis[now]+1))
				{
					dis[nx*w+ny]=dis[now]+1;
					q.push(make_pair(-dis[nx*w+ny],nx*w+ny));
				}
			}
			if(sp[x][y]>='a' && sp[x][y]<='z')
			{
				int c=sp[x][y]-'a';
				if(dis[c+h*w]==-1 || dis[c+h*w]>dis[now])
				{
					dis[c+h*w]=dis[now];
					q.push(make_pair(-dis[c+h*w],c+h*w));
				}
			}
		} else {
			int c=now-h*w;
			for(int i=0;i<gg[c].size();i++)
			{
				if(dis[gg[c][i]]==-1 || dis[gg[c][i]]>dis[now]+1)
				{
					dis[gg[c][i]]=dis[now]+1;
					q.push(make_pair(-dis[gg[c][i]],gg[c][i]));
				}
			}
		}
	}
	// cout<<dis[dp(0,1)]<<" "<<dis[]
	printf("%d\n",dis[tx*w+ty]);
	return 0;
}

#include <stdio.h>
#include <stdlib.h>

#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <stdint.h>
#include <string.h>

#define _USE_MATH_DEFINES
#include <math.h>

#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <deque>
#include <string>

#include <algorithm>
#include <functional>
#include <bitset>
#include <functional>
#include <chrono>
#include <random>

#define sqr(x) (x) * (x)

typedef unsigned int u32;
typedef int i32;
typedef unsigned long long int u64;
typedef long long int i64;
typedef uint16_t u16;
typedef int i16;
typedef uint8_t u8;
typedef int8_t i8;

using namespace std;
using namespace std::chrono;

const i64 mod = 1'000'000'000ll + 7;
//const i64 mod = 998'244'353ll;

const i64 inf = 1'000'000'000'000'000'000ll;

const long double eps = 1e-8;

i64 h, w;

i64 ind(pair<i64, i64> p) {
    return p.first * w + p.second;
}

int main(int argc, char* argv[]) {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout.precision(15); cout.setf(ios::fixed); cerr.precision(15); cerr.setf(ios::fixed);

    if (sizeof(i64) != sizeof(long long int)) {
        cerr << "i64 != long long int" << endl;
    }

    cin >> h >> w;

    vector<string> a(h);
    for (i64 i = 0; i < h; i++) {
        cin >> a[i];
    }

    vector<vector<pair<i64, i64>>> z(256);
    for (i64 i = 0; i < h; i++) {
        for (i64 j = 0; j < w; j++) {
            char c = a[i][j];
            z[c].push_back({ i, j });
        }
    }
    z['.'].clear();

    auto s = z['S'].front();
    auto f = z['G'].front();

    vector<pair<i64, i64>> q;
    vector<i64> v(h * w);
    vector<i64> len;

    q.push_back(s);
    v[ind(s)] = 1;

    len.push_back(q.size());

    for (i64 i = 0; i < q.size(); i++) {
        if (len.back() == i) {
            len.push_back(q.size());
        }

        auto c = q[i];
        if (c == f) {
            cout << len.size() - 1 << endl;
            return 0;
        }

        for (auto x : {c.first - 1, c.first + 1}) {
            auto y = c.second;
            if (x < 0 || x >= h) {
                continue;
            }
            if (y < 0 || y >= w) {
                continue;
            }
            if (a[x][y] == '#') {
                continue;
            }

            pair<i64, i64> nxt = { x, y };
            if (v[ind(nxt)]) {
                continue;
            }
            v[ind(nxt)] = 1;
            q.push_back(nxt);
        }

        for (auto y : { c.second - 1, c.second + 1 }) {
            auto x = c.first;
            if (x < 0 || x >= h) {
                continue;
            }
            if (y < 0 || y >= w) {
                continue;
            }
            if (a[x][y] == '#') {
                continue;
            }

            pair<i64, i64> nxt = { x, y };
            if (v[ind(nxt)]) {
                continue;
            }
            v[ind(nxt)] = 1;
            q.push_back(nxt);
        }

        char w = a[c.first][c.second];
        for (auto nxt : z[w]) {
            if (v[ind(nxt)]) {
                continue;
            }
            v[ind(nxt)] = 1;
            q.push_back(nxt);
        }
        z[w].clear();
    }

    cout << -1 << endl;

    return 0;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <set>
#include <string>
#include <queue>
#include <algorithm>
#include <map>
#include <cmath>
#include <numeric>
#include <list>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <tuple>
#include <deque>
#include <complex>
#include <bitset>
#include <functional>
#include <cassert>
//#include <atcoder/all>

using namespace std;
//using namespace atcoder;

using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
using ld = long double;
using vld = vector<ld>;
using vb = vector<bool>;

#define rep(i, n) for (ll i = 0; i < (n); i++)
#ifdef LOCAL
#define dbg(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl
#else
#define dbg(x) true
#endif

template <class T> void chmin(T& a, T b) { a = min(a, b);}
template <class T> void chmax(T& a, T b) { a = max(a, b);}
template <class T> ostream& operator<<(ostream& s, const vector<T>& a) { for(auto i : a) s << i << ' '; return s; }

constexpr ll INFL = 1LL << 60;
constexpr ld EPS = 1e-12;
ld PI = acos(-1.0);

struct mint {
    static const long long mod = 998244353;
    long long x;
    mint(long long x = 0) : x((x % mod + mod) % mod) {}
    mint operator-() const { return mint(-x);}
    mint& operator+=(const mint& a) {if ((x += a.x) >= mod) x -= mod; return *this;}
    mint& operator-=(const mint& a) {if ((x += mod - a.x) >= mod) x -= mod; return *this;}
    mint& operator*=(const mint& a) {(x *= a.x) %= mod; return *this;}

    friend const mint operator+(const mint& a, const mint& b) { mint ret = a; return ret += b; }
    friend const mint operator-(const mint& a, const mint& b) { mint ret = a; return ret -= b; }
    friend const mint operator*(const mint& a, const mint& b) { mint ret = a; return ret *= b; }
    friend ostream& operator<<(ostream& s, const mint& a) { return s << a.x; }

    mint pow(long long t) const {
        if (!t) return 1;
        mint a = pow(t >> 1);
        a *= a;
        if (t & 1) a *= *this;
        return a;
    }

    // for prime mod
    mint inv() const { return pow(mod - 2);}
    mint& operator/=(const mint a) { return (*this) *= a.inv();}
    friend const mint operator/(const mint& a, const mint& b) { mint ret = a; return ret /= b; }
};

void solve() {
    ll h, w, k;
    cin >> h >> w >> k;
    vector<string> s(h, string(w, '.'));
    rep(i, k) {
        ll h_, w_;
        char c_;
        cin >> h_ >> w_ >> c_;
        s[h_-1][w_-1] = c_;
    }
    /*
    rep(i, h) {
        rep(j, w) cout << s[i][j] << ' ';
        cout << endl;
    }
    */
    using vm = vector<mint>;
    vector<vm> dp(h, vm(w));
    dp[0][0] = mint(3).pow(h*w-k);
    mint inv3 = mint(3).inv();
    rep(i, h) rep(j, w) {
        if(i > 0) {
            if(s[i-1][j] == '.') dp[i][j] += dp[i-1][j] * 2 * inv3;
            else if(s[i-1][j] == 'D' || s[i-1][j] == 'X') dp[i][j] += dp[i-1][j];
        }
        if(j > 0) {
            if(s[i][j-1] == '.') dp[i][j] += dp[i][j-1] * 2 * inv3;
            else if(s[i][j-1] == 'R' || s[i][j-1] == 'X') dp[i][j] += dp[i][j-1];
        }
    }
    cout << dp[h-1][w-1] << endl;
    /*
    rep(i, h) {
        rep(j, w) cout << dp[i][j] << ' ';
        cout << endl;
    }
    */
    return;
}

int main() {
    std::cin.tie(nullptr);
    std::ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(15);
    solve();
}

#include<bits/stdc++.h>
using namespace::std;

const int N = 5000 + 10;
const int MOD = 998244353;
const int F = (2LL * 332748118) % MOD;

int n;
int m;
int k;
int fact;
char v[N][N];
int memo[N][N];

int add(int a, int b){
	return (a + b) % MOD;
}

int mul(int a, int b){
	return (1LL * a * b) % MOD;
}

int pow_mod(int a, int b){
	int r = 1;
	while(b > 0){
		if(b & 1) r = mul(r, a);
		a = mul(a, a);
		b >>= 1;
	}
	return r;
}

int solve(){
	memo[1][1] = 1;
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			if(i + j == n + m) continue;
			if(!isalpha(v[i][j])) memo[i][j] = mul(memo[i][j], F);
			if(isalpha(v[i][j])){
				if(v[i][j] == 'R'){
					memo[i][j + 1] = add(memo[i][j + 1], memo[i][j]);
				}
				else if(v[i][j] == 'D'){

					memo[i + 1][j] = add(memo[i + 1][j], memo[i][j]);
				}
				else{
					memo[i + 1][j] = add(memo[i + 1][j], memo[i][j]);
					memo[i][j + 1] = add(memo[i][j + 1], memo[i][j]);
				}
			}
			else{
				memo[i + 1][j] = add(memo[i + 1][j], memo[i][j]);
				memo[i][j + 1] = add(memo[i][j + 1], memo[i][j]);
			}
		}
	}
	return mul(memo[n][m], pow_mod(3, n * m - k));
}

int main(){
	scanf("%d %d %d", &n, &m, &k);
	memset(v, ' ', sizeof v);
	for(int i = 0; i < k; i++){
		int x, y;
		scanf("%d %d", &x, &y);
		char c = getchar();
		while(!isalpha(c)) c = getchar();
		v[x][y] = c;
	}
	printf("%d\n", solve());
	return 0;
}


#include <bits/stdc++.h>

using namespace std;
using ll = int64_t;
#define rep(i, n) for(int i=0, i##_len=(n); i<i##_len; ++i)

void solve(long long X, long long Y, long long A, long long B) {

    ll exp_a = 0;
    while (true) {
        if (X > Y / A) break;
        if (X * A >= X + B) break;
        if (X * A >= Y) break;

        X *= A;
        exp_a++;
    }
    ll exp_b = floor((long double) (Y - X - 1) / B);
    cout << exp_a + exp_b << endl;
}

int main() {
    long long X;
    scanf("%lld", &X);
    long long Y;
    scanf("%lld", &Y);
    long long A;
    scanf("%lld", &A);
    long long B;
    scanf("%lld", &B);
    solve(X, Y, A, B);
    return 0;
}

#include<cstdio>
#include<cstring>
using namespace std;
bool a[11000];
int main()
{
	memset(a,false,sizeof(a));
	for(int i=6;i<=10000;i+=6)a[i]=true;
	for(int i=10;i<=10000;i+=10)a[i]=true;
	for(int i=15;i<=10000;i+=15)a[i]=true;
	int n;scanf("%d",&n);
	printf("6 10 15");a[6]=a[10]=a[15]=false;
	n-=3;
	for(int i=1;i<=10000;i++)
	{
		if(n==0)return 0;
		if(a[i]){printf(" %d",i);n--;}
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> ii;
typedef tuple<ll, ll, ll> iii;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
#define REP(i,n) for (ll i = 0; i < n; ++i)
#define REPR(i,n) for (ll i = n-1; i >= 0; --i)
#define FOR(i,m,n) for (ll i = m; i < n; ++i)
#define FORR(i,m,n) for (ll i = n-1; i >= m; --i)
#define FORE(x,xs) for (const auto& x : xs)
#define FORI(i,v) for (auto i = v.begin(); i != v.end(); i++)
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define REV(v) reverse(ALL(v))
#define UNIQ(v) sort(ALL(v)); v.erase(unique(ALL(v)),end(v))
#define CHMIN(x,y) x = min(x, y)
#define CHMAX(x,y) x = max(x, y)
#define YES(b) cout << ((b) ? "YES" : "NO") << endl
#define Yes(b) cout << ((b) ? "Yes" : "No") << endl

const int MAX = 1e5+10;

int N, M, K;
set<int> A;

ld dp[2*MAX];

bool check(ld p) {
    fill_n(dp, MAX, 0);
    ld s = 0;
    REPR (i, N) {
        if (A.find(i) == A.end()) dp[i] = 1 + s / M;
        else dp[i] = p;
        s += dp[i];
        s -= dp[i+M];
    }
    return dp[0] > p;
}

int main() {
    cout << fixed << setprecision(15);
    cin >> N >> M >> K;
    REP (i, K) {
        int a;
        cin >> a;
        A.insert(a);
        if (A.find(a-M+1) != A.end() && distance(A.find(a-M+1), A.find(a)) == M-1) {
            cout << -1 << endl;
            return 0;
        }
    }

    ld ub = 1;
    while (1) {
        ld ok = 1e-3, ng = ub;
        while (ng - ok > 1e-4) {
            ld mid = sqrtl(ok * ng);
            if (check(mid)) ok = mid;
            else ng = mid;
        }
        if (ub - ok > 1e3) {
            cout << ok << endl;
            return 0;
        }
        ub *= 4;
    }
}