#include <cstdio>
#include <iostream>
#include <cassert>
#include <string>
#include <algorithm>
#include <cstring>
#include <utility>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <unordered_map>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)

using namespace std;
using namespace __gnu_pbds;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> order_set;

const int MAXN = 234567;
char S[MAXN], T[123] = "110";

int main() {
    int N;
    scanf("%d", &N);
    scanf("%s", S);
    LL ans = 0;
    for (int i = 0; i < 3; i++) {
        bool OK = true;
        for (int j = 0; j < N; j++) {
            if (S[j] != T[(i + j) % 3]) {
                OK = false;
                break;
            }
        }
        if (OK) {
            LL sum = (LL)1e10;
            LL need = (i + N - 1) / 3 + 1;
            ans += (sum - need + 1);
        }
    }
    printf("%lld\n", ans);
    return 0;
}
/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
by Benq;
*/

#include <bits/stdc++.h>

using namespace std;

int a, b, ans;

int check(int a, int b) {
    if (a+b >= 15 && b >= 8) return 1;
    if (a+b >= 10 && b >= 3) return 2;
    if (a+b >= 3) return 3;
    return 4;
}

int main() {
    //freopen("isc.inp", "r", stdin);
    //freopen("isc.out", "w", stdout);

    scanf("%d%d", &a, &b);
    ans = check(a, b);

    printf("%d", ans);

    return 0;
}


#include <iostream>

int main() {
  unsigned int N;
  std::cin >> N;

  int cnt = 0;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; ++j) {
      if (i+j == N) cnt++;
    }
  }
  std::cout << cnt;
  return 0;
}

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

int main(){
	int n;
	cin>>n;
	cout<<n-1<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[65];
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        string s;
        cin>>s;
        if(s == "AND") a[i] = 1;
        else a[i] = 0;
    }
    ll t = 1,f = 1;
    for(int i=0;i<n;i++){
        if(a[i] == 1) {
            t = t;
            f = (ll)f*2+t;
        }
        else{
            t = (ll)t*2+f;
            f = f;
        }
    }
    cout<<t<<endl;
    return 0;
}

#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<map>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<stack>
#include<queue>
#include<tuple>
#include<cassert>
#include<set>
#include<bitset>
#include<functional>
#include <fstream>
//#include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, x) for(ll i = 0; i < x; i++)
#define rep2(i, x) for(ll i = 1; i <= x; i++)
#define all(a) (a).begin(),(a).end()
#define puts(x) cout << (x) << "\n"
using ll = long long;
using ld = long double;
using namespace std;
const ll INF = 10000000000000000;
const int intINF = 1000000000;
const ll mod = 1000000007;
const ll MOD = 998244353;
const ld pi = 3.141592653589793238;

bool isprime(int p) {
	if (p == 1) return false;
	for (int i = 2; i < p; i++) {
		if (p % i == 0) return false;
	}
	return true;
}
ll gcd(ll a, ll b) {
	if (a < b)swap(a, b);
	if (a % b == 0)return b;
	return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
	return a / gcd(a, b) * b;
}
ll keta(ll n) {
	ll res = 0;
	while (n >= 1) {
		res += n % 10; n /= 10;
	}
	return res;
}
ll modpow(ll x, ll y) {
	ll res = 1;
	while (y) {
		if (y % 2) { res *= x; res %= mod; }
		x = x * x % mod; y /= 2;
	}
	return res;
}
ll nCk(ll n, ll k) {
	ll a = 1, b = 1;
	for (int h = n - k + 1; h <= n; h++) { a *= h; a %= mod; }
	for (int h = 1; h <= k; h++) { b *= h; b %= mod; }
	return a * modpow(b, mod - 2) % mod;
}
//printf("%.10f\n", n);
typedef pair <ll, ll> P;
ll dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };
struct edge { ll to, cost; };
struct status {
	ll cost;
	ll x;
	ll y;

	bool operator<(const status& rhs) const { return cost < rhs.cost; };
	bool operator>(const status& rhs) const { return cost > rhs.cost; };
};

signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//cout << fixed << setprecision(15);

	ll n; cin >> n;
	vector<string> v(n);
	rep(i, n) { cin >> v[i]; }
	vector<ll> t(n + 2), f(n + 2);
	t[n] = 1;
	for (int i = n - 1; i >= 0; i--) {
		if (v[i] == "AND") { t[i] = t[i + 1] + f[i + 1]; f[i] = 2 * f[i + 1]; }
		else { t[i] = 2 * t[i + 1]; f[i] = t[i + 1] + f[i + 1]; }
	}
	cout << t[0] + f[0] << endl;
	return 0;
}


#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;

long long N;
long long fib[1 << 18];

void init() {
	fib[0] = 1; fib[1] = 1;
	for (int i = 2; i <= 90; i++) fib[i] = fib[i - 1] + fib[i - 2];
}

int main() {
	cin >> N;
	init();

	long long idx = -1, rem = -1;
	for (int i = 1; i <= 89; i++) {
		if (fib[i] > N) { idx = i - 1; rem = N - fib[i - 1]; break; }
	}

	string S = "";
	for (int i = 1; i <= idx; i++) {
		if (i % 2 == 1) S = "3" + S;
		if (i % 2 == 0) S = "4" + S;
	}
	if (S[0] == '4') S = "1" + S;
	else S = "2" + S;

	for (int i = 89; i >= 1; i--) {
		if (rem < fib[i]) continue;
		rem -= fib[i];
		int cnt = 0;
		for (int j = (int)S.size() - 1; j >= 0; j--) {
			if (S[j] == '3' || S[j] == '4') cnt++;
			if (cnt == i + 1) {
				string T1 = S.substr(0, j + 1);
				string T2 = S.substr(j + 1, S.size() - (j + 1));
				string U = "";
				if (S[j] == '3') U = T1 + "1" + T2;
				if (S[j] == '4') U = T1 + "2" + T2;
				S = U;
				break;
			}
		}
	}

	cout << S.size() << endl;
	for (int i = 0; i < S.size(); i++) cout << S[i] << endl;
	return 0;
}

#include<bits/stdc++.h>
#define N 5000005
using namespace std;
int read() {
	int x=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while('0'<=c&&c<='9'){x=x*10+c-'0';c=getchar();}
	return x*f;
}
int n,a[N],b[N],ans;
bool tag[2005];
int main() {
	n = read();
	for(int i=1; i<=n; ++i)a[i] = read();
	for(int i=1; i<=n; ++i) {
		for(int j=1; j<=sqrt(a[i]); ++j) {
			if(a[i]%j == 0)b[++b[0]] = j,b[++b[0]] = a[i]/j;
		}
	}
	sort(b+1,b+b[0]+1);
	b[0] = unique(b+1,b+b[0]+1)-b-1;
	for(int i=1; i<=b[0]; ++i) {
		int x = b[i],now = 0,id,suc;
		memset(tag,0,sizeof(tag));
		for(int j=1; j<=n; ++j)if(a[j]%x == 0){suc = now = a[j];id = j+1;tag[j] = 1;break;}
		for(int j=id; j<=n; ++j) {
			if(a[j]%x == 0)now = __gcd(now,a[j]),tag[j] = 1;
		}
		if(now == x)suc = 1;
		else suc = 0;
		for(int j=1; j<=n; ++j)if(now > a[j])suc = 0;
		ans += suc;
	}
	cout << ans;
}


//https://atcoder.jp/contests/abc187/tasks/abc187_d
//D - Choose Me
#include <bits/stdc++.h>

using namespace std;

//如果提交到OJ，不要定义 __LOCAL
//#define __LOCAL

typedef long long ll;

const int MAXN=2e5+4;
ll vote[MAXN];

int main() {
#ifndef __LOCAL
    //这部分代码需要提交到OJ，本地调试不使用
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#endif
    int n;
    cin>>n;
    ll avote=0;
    for (int i=1; i<=n; i++) {
        ll a,b;
        cin>>a>>b;
        avote += -a;//记录a的票数
        vote[i] = 2*a+b;
    }

    sort(vote+1, vote+n+1, greater<ll>());

    //遍历求解
    int ans=0;
    for (int i=1; i<=n; i++) {
        avote += vote[i];
        if (avote>0) {
            ans=i;
            break;
        }
    }
    cout<<ans<<"\n";

#ifdef __LOCAL
    //这部分代码不需要提交到OJ，本地调试使用
    system("pause");
#endif
    return 0;
}

#include <iostream>
#include <bits/stdc++.h>
#include <bitset>
#define ll long long int
#define pi pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define vi vector<int>
#define vl vector<ll>
#define vll vector<vl>
#define vpi vector<pi>
#define vpll vector<pll>
#define vb vector<bool>
#define vii vector<vi>
#define ALL(v) v.begin(), v.end()
#define st string
#define si(n) cin >> n
#define dout(n) cout << n << "\n"
#define mod 1000000007
#define f(i, a, b) for (int i = a; i < b; i++)
#define fd(i, a, b) for (int i = a; i >= b; i--)

using namespace std;

bool yes = false;
st s1, s2;

ll max(ll a, ll b, ll c)
{
    return max(a, max(b, c));
}

struct comp
{

    bool operator()(const pi &a, const pi &b)
    {
        if (a.first == b.first)
            return a.second < b.second;
        return a.first < b.first;
    }
};

bool check_pal(st &s)
{
    int i = 0, j = s.length() - 1;
    while (i < j)
    {
        if (s[i] != s[j])
            return false;
        i++, j--;
    }
    return true;
}
void swap(char &a, char &b)
{
    char ch = a;
    a = b;
    b = ch;
    return;
}
int dfs(vii &g, vi &vis, vi &co, int pos)
{

    int mn = co[pos];
    vis[pos] = 1;
    f(i, 0, g[pos].size())
    {
        if (!vis[g[pos][i]])
            mn = min(dfs(g, vis, co, g[pos][i]), mn);
    }
    return mn;
}

void seive(int n, vector<bool> &isprime)
{
    isprime[0] = true;
    isprime[1] = true;
    f(i, 2, n + 1)
    {
        if (!isprime[i])
        {

            for (int j = 2; (j * i) < n + 1; j++)
                isprime[j * i] = true;
        }
    }
}
int findfact( int n , int&a , int &b){
    for( int i =2 ;i<n ; i++){
        if( n%i == 0 && i!=n/i) {
            a=i;
            b = n/i ;
            return 0;
        }
    }
    return -1;
}
ll ignoref(vi & v, int mx , int fmx , vi & con, int idx){
ll op=0;
int n = v.size();
int prev = idx == 0? v[1]:v[0];
if( fmx==1){
      f(i,1,n){
           if( v[i]!=mx){
                 op+= abs(v[i]-prev);
                 //cout<<op<<" ";
                 prev = v[i];
           }

       }
}
else {
    int index;
    int mxcon=INT_MIN;
    f(i,0,n){
        if(v[i]==mx){
            if( mxcon <con[i]){
                index =i;
                mxcon = con[i];
            }
        }
    }
    f(i,1,n){
           if( i!= index){
                 op+= abs(v[i]-prev)*1ll;
               //  cout<<op<<" "<<v[i]<<" "<<prev<<" \n";
                 prev = v[i];
           }

       }
}
return op;
}

int main()
{

 int n;
 cin>>n;
 vi v;
 f(i,0,n){
     int a;
     cin>>a;
     v.pb(a);
 }
 vector<pair<ll,ll>>pssum(n);
 ll msf=0,mx=0;
 f(i,0,n){
     msf+=v[i];
     mx = max(mx,msf);
     pssum[i].first = mx;
     pssum[i].second = msf;
 }
 ll ans = 0;
 msf =0;
 f(i,0,n){
     ans = max(msf+pssum[i].first, ans);
    msf+=pssum[i].second;

 }
 ans = max(msf,ans);
 cout<<ans<<"\n";
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

#define int long long
#define sim template <class c
#define ris return *this
#define dor > debug& operator<<
#define eni(x)                                                                 \
    sim > typename enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(   \
              c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c> {i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifndef LOCAL
	~debug() { cerr << endl; }
	eni( != ) cerr << boolalpha << i;
	ris;
} eni( == ) ris << range(begin(i), end(i));
}
sim, class b dor(pair<b, c> d) {
	ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
	*this << "[";
	for (auto it = d.b; it != d.e; ++it)
		*this << ", " + 2 * (it == d.b) << *it;
	ris << "]";
}
#else
	sim dor(const c&) { ris; }
#endif
}
;
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

template <typename T>
using indexed_set =
    tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template <class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }

#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define in insert
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define sz(v) (int)(v.size())
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define mem(a, s) memset(a, s, sizeof(a))
#define rep(i, a, b) for (int i = a; i <= b; ++i)
#define repr(i, a, b) for (int i = a; i >= b; --i)
#define MAX 8000000000000000064LL
#define MIN -8000000000000000064LL

typedef vector<int> vi;
typedef stack<int> sti;
typedef queue<int> qi;
typedef pair<int, int> pii;
typedef set<int> si;
typedef map<int, int> mii;
typedef vector<pii> vpi;
typedef priority_queue<int> pqmax;
typedef priority_queue<int, vector<int>, greater<int>> pqmin;

const int mod = 1e9 + 7;
const int inf = 1e18;
const int d4x[4] = { -1, 0, 1, 0}, d4y[4] = {0, 1, 0, -1};
const int d8x[8] = { -1, -1, 0, 1, 1, 1, 0, -1}, d8y[8] = {0, 1, 1, 1, 0, -1, -1, -1};

void solve();

int32_t main() {

	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	cout.precision(20);

	int t = 1;
	// cin >> t;
	rep(i, 1, t) {
		// cout << "Case #" << i << ": ";
		solve();
	}

	return 0;
}

void solve() {
	int n;
	cin >> n;
	vector<pii> v;
	rep(i, 0, n - 1) {
		int x, y;
		cin >> x >> y;
		v.pb(mp(x, y));
	}
	int count = 0;
	bool flag = 0;
	rep(i, 0, n - 1) {
		rep(j, i + 1, n - 1) {
			rep(k, j + 1, n - 1) {
				if ((v[j].se - v[i].se) * (v[k].fi - v[j].fi) == (v[k].se - v[j].se) * (v[j].fi - v[i].fi)) {
					flag = 1;
					break;
				}
			}
		}
	}
	(flag == 0) ? cout << "No\n" : cout << "Yes\n";
}

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

int main() {
    typedef long long ll;
    ll n;
    cin >> n;
    vector<ll> x;
    vector<ll> y;
    bool isYes = false;

    for(int i=0; i<n; i++){
        ll a, b;
        cin >> a >> b;
        x.push_back(a);
        y.push_back(b);
    }

    for(int i=0; i<n-2; i++){
        for(int j=i+1; j<n-1; j++){
            for(int k=j+1; k<n; k++){
                // cout << i << "," << j << "," << k <<"." << endl;
                ll dx1 = x[i] - x[j];
                ll dx2 = x[i] - x[k];
                ll dy1 = y[i] - y[j];
                ll dy2 = y[i] - y[k];
                if(dx2*dy1 == dx1*dy2){
                    cout << "Yes" << endl;
                    return 0;
                }
            }
        }
    }
    cout << "No" << endl;
    return 0;
}


#define LOCAL
#define _USE_MATH_DEFINES
#include <array>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <complex>
#include <cmath>
#include <numeric>
#include <bitset>
#include <functional>
#include <random>
#include <ctime>

using namespace std;

template <typename A, typename B>
ostream& operator <<(ostream& out, const pair<A, B>& a) {
  out << "(" << a.first << "," << a.second << ")";
  return out;
}
template <typename T, size_t N>
ostream& operator <<(ostream& out, const array<T, N>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T>
ostream& operator <<(ostream& out, const vector<T>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T, class Cmp>
ostream& operator <<(ostream& out, const set<T, Cmp>& a) {
  out << "{"; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "}";
  return out;
}
template <typename U, typename T, class Cmp>
ostream& operator <<(ostream& out, const map<U, T, Cmp>& a) {
  out << "{"; bool first = true;
  for (auto& p : a) { out << (first ? "" : ", "); out << p.first << ":" << p.second; first = 0;} out << "}";
  return out;
}
#ifdef LOCAL
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
#else
#define trace(...) 42
#endif
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << ": " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << ": " << arg1 << " |";
  __f(comma + 1, args...);
}

typedef long long int64;
typedef pair<int, int> ii;
#define SZ(x) (int)((x).size())
const int INF = 1 << 29;
const int MOD = 1e9 + 7;
mt19937 mrand(random_device{}());
int rnd(int x) { return mrand() % x; }

struct fast_ios {
  fast_ios() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
  };
} fast_ios_;

int main() {
  int n, m;
  cin >> n >> m;
  vector<int> a(n + 2), b(n + 2);
  a[0] = 0; a[n + 1] = m + 1;
  for (int i = 1; i <= n; ++i) cin >> a[i];
  map<int, int> mi, mx;
  for (int i = 0; i <= n + 1; ++i) {
    int x = a[i] - i;
    if (mi.find(x) == mi.end()) {
      mi[x] = i;
    } else {
      mi[x] = min(mi[x], i);
    }
    if (mx.find(x) == mx.end()) {
      mx[x] = i;
    } else {
      mx[x] = max(mx[x], i);
    }
  }
  // trace(mi, mx);
  vector<int> left(n + 2, INF), right(n + 2, -INF);
  bool found = false;
  for (int i = 1; i <= n; ++i) {
    cin >> b[i];
    int x = b[i] - i;
    if (mi.find(x) == mi.end()) {
      found = true;
      continue;
    }
    int L = mi[x], R = mx[x];
    if (i >= L && i <= R) continue;
    if (i < L) {
      left[L] = min(left[L], i);
    } else {
      right[R] = max(right[R], i);
    }
  }
  if (found) {
    cout << -1 << '\n';
    return 0;
  }

  int64 ret = 0;
  for (int i = 0; i <= n + 1; ++i) {
    // trace(i, left[i], right[i]);
    ret += max(0, i - left[i]);
    ret += max(0, right[i] - i);
  }
  cout << ret << '\n';

  return 0;
}

#include <bits/stdc++.h>
using Int = long long;  // clang-format off
#define REP_(i, a_, b_, a, b, ...) for (Int i = (a), lim##i = (b); i < lim##i; i++)
#define REP(i, ...) REP_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__)
#define ALL(v) std::begin(v), std::end(v)
struct SetupIO { SetupIO() { std::cin.tie(nullptr), std::ios::sync_with_stdio(false), std::cout << std::fixed << std::setprecision(13); } } setup_io;
#ifndef dump
#define dump(...)
#endif  // clang-format on
struct in {
    template <class T> operator T() {
        T t;
        std::cin >> t;
        return t;
    }
};
void out() { std::cout << "\n"; }
template <class Head, class... Tail> void out(Head&& h, Tail&&... t) {
    std::cout << h << (sizeof...(Tail) == 0 ? "" : " "), out(std::forward<Tail>(t)...);
}

/**
 *    author:  knshnb
 *    created: Sun Oct 18 22:11:15 JST 2020
 **/

template <class T> bool chmin(T& a, const T& b) { return a > b ? a = b, true : false; }
template <class T> bool chmax(T& a, const T& b) { return a < b ? a = b, true : false; }

/// @docs src/Helper/BinarySearch.md
template <class F> long long binary_search(long long ok, long long ng, F check) {
    while (std::abs(ok - ng) > 1) {
        long long mid = (ok + ng) / 2;
        (check(mid) ? ok : ng) = mid;
    }
    return ok;
}

void no() {
    out(-1);
    exit(0);
}
signed main() {
    Int n = in(), L = in();
    std::vector<Int> a(n), b(n);
    REP(i, n) a[i] = in();
    REP(i, n) b[i] = in();
    std::vector<Int> xs = {0};
    for (Int x : a) xs.push_back(x);
    xs.push_back(L + 1);
    std::vector<Int> vec(n);
    REP(i, n) {
        if (a[i] > b[i]) {
            Int idx = binary_search(0, i + 1, [&](Int mid) { return xs[mid] + i + 1 - mid <= b[i]; });
            if (xs[idx] + i + 1 - idx != b[i]) no();
            vec[i] = idx;
        } else if (a[i] < b[i]) {
            Int idx = binary_search(n + 1, i + 1, [&](Int mid) { return xs[mid] - (mid - (i + 1)) >= b[i]; });
            if (xs[idx] - (idx - (i + 1)) != b[i]) no();
            vec[i] = idx;
        } else {
            vec[i] = i + 1;
        }
    }
    dump(vec);
    REP(i, n - 1) {
        if (vec[i] > vec[i + 1]) no();
    }
    std::vector<Int> pma(n + 2), nma(n + 2);
    REP(i, n) {
        Int dif = vec[i] - (i + 1);
        if (dif > 0) chmax(pma[vec[i]], dif);
        if (dif < 0) chmax(nma[vec[i]], -dif);
    }
    out(std::accumulate(ALL(pma), 0LL) + std::accumulate(ALL(nma), 0LL));
}


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

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

const int MAX = 10010;
class shuturyoku_unko {
public:
	char C[MAX * 6];
	constexpr shuturyoku_unko() : C() {
		rep(i, MAX) {
			int X = i;
			rep(j, 5) {
				C[i * 6 + 4 - j] = '0' + X % 10;
				X /= 10;
			}
			C[i * 6 + 5] = ' ';
		}
	}
};
constexpr shuturyoku_unko f;

char T[800], *ci = T, c, *di;
int N, A[110], B[110];
bool furagu[10001];
inline void keisan(int s) {
	di = T;
	rep(i, N + 1) {
		int tmp = A[i] + (B[i] > s);
		int tmp2;
		if (tmp >= 1000) {
			if (tmp >= 10000) tmp2 = 6;
			else tmp2 = 5;
		}
		else {
			if (tmp >= 100) tmp2 = 4;
			else if (tmp >= 10) tmp2 = 3;
			else tmp2 = 2;
		}
		memcpy(di, f.C + tmp * 6 + 6 - tmp2, tmp2);
		di += tmp2;
	}
}

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

	fread(T, 800, 1, stdin);
	while ((c = *ci++) >= '0') N = N * 10 + c - '0';
	ci += N + 1;
	rep(i, N + 1) {
		while ((c = *ci++) >= '0') A[i] = A[i] * 10 + c - '0';
	}

	int saishou = 1e9;
	rep(i, N) if (saishou > abs(A[i] - A[i + 1])) saishou = abs(A[i] - A[i + 1]);

	rep(i, N + 1) {
		B[i] = A[i] % saishou;
		A[i] = A[i] / saishou;
		furagu[B[i]] = 1;
	}

	printf("%d\n", saishou);
	keisan(0);
	rep(s, saishou) {
		if (furagu[s]) keisan(s);
		fwrite(T, 1, di - T, stdout);
	}

	Would you please return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep2(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define ALL(obj) (obj).begin(), (obj).end()
#define rALL(obj) (obj).rbegin(), (obj).rend()
const ll INF = 1LL<<60;//1152921504606846976
const int mod = 1000000007;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll n; cin>>n;
    string s;cin>>s;
    vector<ll> a(n+1);rep(i,n+1)cin>>a[i];
    ll ans = INF;
    rep(i,n)ans = min(ans, abs(a[i+1]-a[i]));
    vector<vector<ll>> b(ans, vector<ll>(n+1,0));
    rep(i,n+1){
        ll idx = 0;
        while(a[i]){
            b[idx][i]++;
            a[i]--;
            idx++;
            idx%=ans;
        }
    }
    cout<<ans<<endl;
    rep(i,ans){
        rep(j,n+1){
            cout<<b[i][j]<<" ";

        }
        cout<<endl;
    }
    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <assert.h>
typedef long long ll;
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;

template <class T> void input(T& a){
    cin>>a;
}

int main(){

  int N;
  input(N);
  ll ans=0;

  vector <int>A(N);
  vector <int>B(200);

  rep(i,N)cin>>A[i];
  rep(i,N){
    A[i] = A[i]%200;
  }

  rep(i,N){
    B[A[i]]++;
  }

  rep(i,200){
      ans += (ll)B[i]*(B[i]-1)/2;
  }
  cout << ans << endl;
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int n,a[N];
double m,p,s,t;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]),p+=a[i];
	sort(a+1,a+n+1);
	m=p;
	for(int i=1;i<=n;i++)
	{
		p-=a[i];
		double s=p,t=a[i]/2.0;
		s+=t*(i*2-n);
		m=min(m,s);
	}
	printf("%.9lf\n",m/n);
	return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

typedef long long ll;
#define ci const int
inline int max(ci &x, ci &y) {return x > y ? x : y;}
inline int min(ci &x, ci &y) {return x < y ? x : y;}
inline void swap(int &x, int &y) {x ^= y ^= x ^= y;}
inline void chmax(int &x, ci &y) { if(x < y) x = y; }
inline void chmin(int &x, ci &y) { if(x > y) x = y; }
#define rei register int
#define rep(i, l, r) for(rei i = l, i##end = r; i <= i##end; ++ i)
#define per(i, r, l) for(rei i = r, i##end = l; i >= i##end; -- i)
char inputbuf[1 << 23], *p1 = inputbuf, *p2 = inputbuf;
#define getchar() (p1 == p2 && (p2 = (p1 = inputbuf) + fread(inputbuf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
inline int read() {
	int res = 0; char ch = getchar(); bool f = true;
	for(; ch < '0' || ch > '9'; ch = getchar())
		if(ch == '-') f = false;
	for(; ch >= '0' && ch <= '9'; ch = getchar())
		res = res * 10 + (ch ^ 48);
	return f ? res : -res;
}
const int N = 305;
int a, b, c;
signed main() {
	a = read(); b = read(); c = read();
	if(b < a) swap(a, b);
	if(c < a) swap(c, a);
	printf("%d\n", b + c);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define N 805
#define MAX_A 1000000000
#define rep(i, n) for(int i = 0; i < n; ++i)
int main(void) {
	int n, k, lim;
	int a[N][N];
	int s[N][N];
	rep(i, N) {
		s[i][0] = 0;
		s[0][i] = 0;
	}
	int ng = -1;
	int ok = MAX_A;
	int mid;
	bool ext;
	cin >> n >> k;
	lim = ((k*k) / 2) + 1;
	rep(i, n) {
		rep(j, n)cin >> a[i][j];
	}
	while ((ng + 1) < ok) {
		mid = (ng + ok) / 2;
		rep(i, n) {
			rep(j, n) {
				s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j];
				if (a[i][j] > mid)s[i + 1][j + 1]++;
			}
		}
		ext = false;
		rep(i, n - k + 1) {
			rep(j, n - k + 1) {
				if ((s[i + k][j + k] + s[i][j] - s[i][j + k] - s[i + k][j]) < lim)ext = true;
			}
		}
		if (ext)ok = mid;
		else ng = mid;
	}
	cout << ok << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
#define F first
#define S second
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define read(v) for(auto &it:v) cin>>it;
#define deb(x) cout << ">" << #x << '=' << x << endl;
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define inf LLONG_MAX
const ll N = 2e5 + 5;
ll MOD = (ll)(1e9 + 7);

vector<pair<int,int> > adj[N];
vector<int> vis(N);
vector<int> value(N);
int n,k;
void dfs(int node,int val){
	value[node]=((val>n)?1:val);
	vis[node]=true;
	for(auto it:adj[node]){
         if(!vis[it.F]){
         	   if(it.S==value[node])
         	   	dfs(it.F,value[node]+1);
         	   else
         	   	dfs(it.F,it.S);
         }
	}
}
void solve() {
   cin>>n>>k;
   for(int i=0;i<=n;i++){
   	  adj[i].clear();
   	  vis[i]=false;
   }
   while(k--){
   	  int u,v,z;
   	  cin>>u>>v>>z;
   	  adj[u].pb({v,z});
   	  adj[v].pb({u,z});
   }

   dfs(1,1);
   for(int i=1;i<=n;i++){
   	  cout<<value[i]<<endl;
   }

}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
#endif
  int t = 1;
  //cin >> t;
  while (t--) solve();
  cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
  return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <numeric>
#include <utility>
#include <tuple>

#define rep(i, a, b) for (int i = int(a); i < int(b); i++)
using namespace std;
using ll = long long int;
using P = pair<ll, ll>;

// clang-format off
#ifdef _DEBUG_
#define dump(...) do{ cerr << __LINE__ << ":\t" << #__VA_ARGS__ << " = "; PPPPP(__VA_ARGS__); cerr << endl; } while(false)
template<typename T> void PPPPP(T t) { cerr << t; }
template<typename T, typename... S> void PPPPP(T t, S... s) { cerr << t << ", "; PPPPP(s...); }
#else
#define dump(...) do{ } while(false)
#endif
template<typename T> vector<T> make_v(size_t a, T b) { return vector<T>(a, b); }
template<typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v(ts...))>(a, make_v(ts...)); }
template<typename T> bool chmin(T &a, T b) { if (a > b) {a = b; return true; } return false; }
template<typename T> bool chmax(T &a, T b) { if (a < b) {a = b; return true; } return false; }
template<typename T> void print(T a) { cout << a << '\n'; }
template<typename T, typename... Ts> void print(T a, Ts... ts) { cout << a << ' '; print(ts...); }
template<typename T> istream &operator,(istream &in, T &t) { return in >> t; }
// clang-format on

class UnionFind {
public:
    vector<int> par;
    int N;
    UnionFind(int n) {
        par.resize(n, -1);
        N = n;
    }
    int Find(int n) {
        return par[n] < 0 ? n : par[n] = Find(par[n]);
    }
    bool Union(int x, int y) {
        x = Find(x);
        y = Find(y);
        if (x == y) return false;
        if (-par[x] > -par[y]) swap(x, y);
        par[y] += par[x];
        par[x] = y;
        N--;
        return true;
    }
    bool Same(int x, int y) {
        return Find(x) == Find(y);
    }
    int size(int x) {
        return -par[Find(x)];
    }
    int size() {
        return N;
    }
};

using edge = tuple<int, int>;

#include <set>

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n, m;
    cin, n, m;
    UnionFind uf(n);
    vector<vector<edge>> tree(n);
    rep(i, 0, m) {
        int a, b, c;
        cin, a, b, c;
        a--;
        b--;
        if (!uf.Same(a, b)) {
            uf.Union(a, b);
            tree[a].emplace_back(b, c);
            tree[b].emplace_back(a, c);
        }
    }
    auto get_color = [&](int cur) {
        if (cur == 1) {
            return 2;
        } else {
            return 1;
        }
    };
    vector<int> vertex(n, -1);
    auto rec = [&](auto &f, int cur, int prev) -> void {
        for (auto [nxt, color] : tree[cur]) {
            if (nxt == prev) continue;
            if (vertex[cur] == color) {
                vertex[nxt] = get_color(color);
            } else {
                vertex[nxt] = color;
            }
            f(f, nxt, cur);
        }
    };
    rec(rec, 0, -1);
    set<int> s;
    rep(i, 0, n) {
        s.insert(i + 1);
    }
    for (auto [nxt, color] : tree[0]) {
        s.erase(color);
    }
    vertex[0] = *s.begin();
    rep(i, 0, n) {
        print(vertex[i]);
    }
    return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
const int INF = 1001001001;
const int mod = 1000000007;

// rotation 90 degrees
vvi rot(vvi orginal,int h,int w){
    vvi v(w,vi(h));
    for(int i = 0;i < h;i++){
        for(int j = 0; j < w;j++){
            v.at(w-j-1).at(i) = orginal.at(i).at(j);
        }
    }
    return v;
}

int main(){
    int h,w,n,m;
    cin >> h >> w >> n >> m;
    vvi mas(h,vi(w,0));
    vvi received(h,vi(w,0));
    rep(i,n){
        int a,b;
        cin >> a >> b;
        a--;b--;
        mas.at(a).at(b) = 1;
    }
    rep(i,m){
        int c,d;
        cin >> c >> d;
        c--;d--;
        mas.at(c).at(d) = 2;
    }
    rep(i,4){
        rep(j,h){
            bool f = false;
            rep(k,w){
                if(mas.at(j).at(k) == 2){
                    f = false;
                    continue;
                }
                if(mas.at(j).at(k) == 1){
                    f = true;
                    received.at(j).at(k) = 1;
                    continue;
                }
                if(f) received.at(j).at(k) = 1;
            }
        }
        // cout << "h:" << h << endl;
        // cout << "w:" << w << endl;
        mas = rot(mas,h,w);
        received = rot(received,h,w);
        swap(h,w);
    }
    ll ans = 0;
    rep(i,h)rep(j,w) if (received.at(i).at(j)) ans++;
    cout << ans << endl;

}

#include <iostream>
using namespace std;

int main() {
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    cout<<a*d-b*c<<endl;
	return 0;
}


#include <iostream>
#include <cstdio>
#include <vector>
#include <unordered_set>

using namespace std;

class Solution{

public:
    double solve(int N, int M, int K, const vector<int>& A){

        unordered_set<int> Aset(A.begin(), A.end());
        vector<double> a(N + M, 0.0), b(N + M, 1.0);
        double asum = 0.0, bsum = M;

        for(int i = N - 1; i >= 0; i --){
            if(Aset.count(i))
                a[i] = 1.0, b[i] = 0.0;
            else
                a[i] = asum / M, b[i] = bsum / M + 1.0;

            asum -= a[i + M], asum += a[i];
            bsum -= b[i + M], bsum += b[i];
        }

        if(abs(a[0] - 1) < 1e-8) return -1;
        return - b[0] / (a[0] - 1.0) - 1.0;
    }
};

int main() {

    int N, M, K; cin >> N >> M >> K;

    vector<int> A(K);
    for(int i = 0; i < K; i ++) cin >> A[i];

    double res = Solution().solve(N, M, K, A);
    if(res < 0) cout << -1 << endl;
    else printf("%.4lf", res);

    return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<ll, ll> p_ll;

template<class T>
void debug(T itr1, T itr2) { auto now = itr1; while(now<itr2) { cout << *now << " "; now++; } cout << endl; }
#define repr(i,from,to) for (ll i=(ll)from; i<(ll)to; i++)
#define all(vec) vec.begin(), vec.end()
#define rep(i,N) repr(i,0,N)
#define per(i,N) for (ll i=(ll)N-1; i>=0; i--)

const ll MOD = pow(10,9)+7;
const ll LLINF = pow(2,61)-1;
const ll INF = pow(2,30)-1;

vector<ll> fac;
void c_fac(ll x=pow(10,7)+10) { fac.resize(x,true); rep(i,x) fac[i] = i ? (fac[i-1]*i)%MOD : 1; }
ll inv(ll a, ll m=MOD) { ll b = m, x = 1, y = 0; while (b!=0) { ll d = a/b; a -= b*d; swap(a,b); x -= y*d; swap(x,y); } return (x+m)%m; }
ll nck(ll n, ll k) { return fac[n]*inv(fac[k]*fac[n-k]%MOD)%MOD; }
ll modpow(ll x, ll p) { ll result = 1, now = 1, pm = x; while (now<=p) { if (p&now) { result = result * pm % MOD; } now*=2; pm = pm*pm % MOD; } return result; }
ll gcd(ll a, ll b) { if (a<b) swap(a,b); return b==0 ? a : gcd(b, a%b); }
ll lcm(ll a, ll b) { return a/gcd(a,b)*b; }

int main() {
  ll N, M, K; cin >> N >> M >> K;
  ll A[K]; rep(i,K) cin >> A[i];

  double dp[N+1][2] = {}; rep(i,K) dp[A[i]][1] = 1;
  double rsum[N+1][2] = {};
  per(i,N) {
    if (dp[i][1]!=1) {
      dp[i][0] = (i+1+M>N?rsum[i+1][0]:rsum[i+1][0]-rsum[i+1+M][0])/M + 1;
      dp[i][1] = (i+1+M>N?rsum[i+1][1]:rsum[i+1][1]-rsum[i+1+M][1])/M;
    }
    rsum[i][0] = rsum[i+1][0] + dp[i][0];
    rsum[i][1] = rsum[i+1][1] + dp[i][1];
  }
  // rep(i,N+1) debug(dp[i],dp[i]+2);
  // rep(i,N+1) debug(rsum[i],rsum[i]+2);

  double result = dp[0][1]==1 ? -1 : dp[0][0]/(1-dp[0][1]);
  cout << setprecision(10) << result << endl;
  return 0;
}


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

#define rep(i,n) for(int i = 0; i < n; i++)
#define Rep(i,n) for(int i = 1; i <= n; i++)
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define fin(a) { cout << a << endl; return 0; }
#define debug(a) { cerr << #a << ": " << a << endl; }
#define endl '\n'
#define fi first
#define se second
using lint = long long;
using ld = long double;
using P = pair<int,int>;
using Pl = pair<lint,lint>;
template<class T> using V = vector<T>;
template<class T> using priq     = priority_queue<T>;
template<class T> using priq_inv = priority_queue<T, vector<T>, greater<T>>;
const int dx[] = {0,1,0,-1,1,1,-1,-1};
const int dy[] = {1,0,-1,0,1,-1,-1,1};
template<class T> T ceil(const T &a, const T &b) { return ((a)+(b)-1)/b; }
template<class T> bool chmin(T &a, T b) { if(a > b) { a = b; return 1; } return 0; }
template<class T> bool chmax(T &a, T b) { if(a < b) { a = b; return 1; } return 0; }
template<class T> void YesorNo(T x) { printf(x ? "Yes\n" : "No\n"); }
struct INF { template<class T> operator T() { return numeric_limits<T>::max() / 2; } } INF;

template<class T, class U> istream& operator>>(istream &in, pair<T,U> &p) {
    return in >> p.first >> p.second;
}
template<class T, class U> ostream& operator<<(ostream &out, const pair<T,U> &p) {
    return out << '{' << p.first << ',' << p.second << '}';
}
template<class T> istream& operator>>(istream &in, vector<T> &v) {
    for(auto &&e : v) in >> e;
    return in;
}
template<class T> ostream& operator<<(ostream &out, const vector<T> &v) {
    for(const auto &e : v) out << e << ' ';
    return out;
}

/*----------------------------------------------------------------------------------------------------*/

struct UnionFind { // UnionFindTree

    vector<int> d;
    int group;
    UnionFind(int n): d(n,-1), group(n) {}

    int find(int x) {
        if(d[x] < 0) return x;
        return d[x] = find(d[x]);
    }

    bool unite(int x, int y) {
        x = find(x);
        y = find(y);
        if(x == y) return false;
        if(-d[x] < -d[y]) swap(x,y);
        group--;
        d[x] += d[y];
        d[y] = x;
        return true;
    }

    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return -d[find(x)]; }
};

long long Modpow(long long a, int n, long long mod){
    if(n == 0) return 1;
    if(n%2 == 0){
      long long res = Modpow(a, n/2, mod);
      return res * res % mod;
    }
    return a * Modpow(a, n-1, mod) % mod;
}

int main(){
    int n;
    cin >> n;
    UnionFind uf(n);
    rep(i,n) {
        int a;
        cin >> a;
        a--;
        uf.unite(i,a);
    }
    cout << Modpow(2,uf.group,998244353)-1 << endl;
}

#include<bits/stdc++.h>

int main(){
    using namespace std;
    unsigned long N;
    cin >> N;
    string S;
    cin >> S;
    if(S[0] != S.back())return 0 & puts("1");
    for(unsigned long i{1}; i < N; ++i)if(S[0] != S[i - 1] && S[i] != S.back())return 0 & puts("2");
    puts("-1");
    return 0;
}


//Let's join Kaede Takagaki Fan Club !!
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
#define int long long
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
#define a first
#define b second
#define fi first
#define sc second
#define rng(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())
#define all(x) x.begin(),x.end()
#define si(x) (int)(x.size())

#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif

template<class t,class u> bool chmax(t&a,u b){if(a<b){a=b;return true;}else return false;}
template<class t,class u> bool chmin(t&a,u b){if(b<a){a=b;return true;}else return false;}

template<class t> using vc=vector<t>;

template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
	return os<<"{"<<p.fi<<","<<p.sc<<"}";
}

template<class t> ostream& operator<<(ostream& os,const vc<t>& v){
	os<<"{";
	for(auto e:v)os<<e<<",";
	return os<<"}";
}

template<class T>
void g(T &a){
	cin >> a;
}
template<class T>
void o(const T &a,bool space=false){
	cout << a << (space?' ':'\n');
}
//ios::sync_with_stdio(false);
const ll mod = 1000000007;//998244353
mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
template<class T>
void add(T&a,T b){
	a+=b;
	if(a >= mod) a-=mod;
}
ll modpow(ll x,ll n){
	ll res=1;
	while(n>0){
		if(n&1) res=res*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return res;
}
int n,m,w[100005];
P pp[100005];
int mx[100005];
int dist[8];
void solve(){
	cin>>n>>m;
	rep(i,n)cin>>w[i];
	rep(i,m)cin>>pp[i].b>>pp[i].a;
	sort(pp, pp+m);
	rep(i, m){
		if(!i) mx[i] = pp[i].b;
		else mx[i] = max(mx[i-1], pp[i].b);
	}
	vc<int>p(n); rep(i,n)p[i]=i;
	ll ans = 1e18;
	do{
		rep(i, n){
		    dist[i] = INF;
		}
		dist[n-1] = 0;
		vc<P>edge[8];
		rep(i, n){
			int W = 0;
			rng(j, i, n){
				W += w[p[j]];
				int v = lower_bound(pp, pp+m, mp(W, (ll)-INF)) - pp;
				v--;
				if(v == -1) v = 0;
				else v = mx[v];

				edge[j].pb(mp(i, -v));
			}
		}
		rep(m, n*n+5){
    		rep(i, n){
    		    for(auto a:edge[i]){
    		        if(dist[a.a] > dist[i] + a.b){
    		            dist[a.a] = dist[i] + a.b;
    		            if(m >= n*n) goto bad;
    		        }
    		    }
    		}
		}
		chmin(ans, -dist[0]);
		bad:;
	}while(next_permutation(all(p)));
	if(ans > 5e17) ans = -1;
	cout<<ans<<endl;
}
signed main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cout<<fixed<<setprecision(20);
	int t; t = 1; //cin >> t;
	while(t--) solve();
}

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

typedef long long LL;

const int N=8,M=100000,INF=(1<<30)-1;

int n,m,a[N+9];
struct thing{
  int l,v;
  thing(int L=0,int V=0){l=L;v=V;}
}b[M+9];

bool cmp(const thing &a,const thing &b){return a.v<b.v;}

void into(){
  scanf("%d%d",&n,&m);
  for (int i=1;i<=n;++i)
	scanf("%d",&a[i]);
  for (int i=1;i<=m;++i)
	scanf("%d%d",&b[i].l,&b[i].v);
}

int mx[M+9];

void Get_mx(){
  sort(b+1,b+m+1,cmp);
  mx[0]=0;
  for (int i=1;i<=m;++i) mx[i]=max(mx[i-1],b[i].l);
}

int p[N+9],vis[N+9];
int dp[N+9],ans;

void Get_dp(){
  dp[0]=0;
  for (int i=1;i<=n;++i){
	dp[i]=dp[i-1];
	int sum=p[i];
	for (int j=i-1;j>=1;--j){
	  sum+=p[j];
      dp[i]=max(dp[i],dp[j]+mx[lower_bound(b+1,b+m+1,thing(0,sum),cmp)-b-1]);
	}
  }
  ans=min(ans,dp[n]);
}

void Dfs_ans(int k){
  if (k>n){
	Get_dp();
	return;
  }
  for (int i=1;i<=n;++i)
	if (!vis[i]){
	  p[k]=a[i];
	  vis[i]=1;
	  Dfs_ans(k+1);
	  vis[i]=0;
	}
}

void Get_ans(){
  ans=INF;
  int mx=a[1];
  for (int i=2;i<=n;++i) mx=max(mx,a[i]);
  int mn=b[1].v;
  for (int i=2;i<=m;++i) mn=min(mn,b[i].v);
  if (mx>mn) return;
  Dfs_ans(1);
}

void work(){
  Get_mx();
  Get_ans();
}

void outo(){
  printf("%d\n",ans==INF?-1:ans);
}

int main(){
  into();
  work();
  outo();
  return 0;
}


#include<bits/stdc++.h>
#define N 200005
#define re register
#define ll long long
#define P 998244353
using namespace std;
int n,m,K,q,u;
inline void Rd(int &res){
	re char c;res=0;bool f=0;
	while(c=getchar(),c<48)(c=='-')&&(f=1);
	do res=(res<<3)+(res<<1)+(c^48);
	while(c=getchar(),c>47);
	f&&(res=-res);
}
int f[25][5005];
int fac[N],fac1[N];
inline int C(int n,int m){
	if(n<m)return 0;
	return 1ll*fac[n]*fac1[m]%P*fac1[n-m]%P;
}
int Pow(int x,int k){
	int res=1;
	while(k){
		if(k&1)res=1ll*res*x%P;
		x=1ll*x*x%P;
		k>>=1;
	}
	return res;
}
int main(){
	Rd(n),Rd(m);
	fac[0]=1;for(re int i=1;i<N;i++)fac[i]=1ll*i*fac[i-1]%P;
	fac1[N-1]=Pow(fac[N-1],P-2);for(re int i=N-2;i>=0;i--)fac1[i]=1ll*(i+1)*fac1[i+1]%P;
	int t=1,cnt=0;
	while((t<<1)<=m)t<<=1,cnt++;
	f[cnt+2][0]=1;
	for(re int i=cnt+1;i>=0;i--){
		int res=(1<<i);
		for(re int j=0;j<=n&&res*j<=m;j+=2){
			for(re int k=0;k+res*j<=m;k++)if(f[i+1][k]){
				f[i][res*j+k]=(f[i][res*j+k]+1ll*f[i+1][k]*C(n,j))%P;
			}
		}
	}
	printf("%d\n",f[0][m]);
	return 0;
}

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <vector>
#include <bitset>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <utility>
#include <algorithm>
#include <random>
#include <cmath>
#include <cassert>
#include <climits>
#include <ctime>
#include <chrono>

/*
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,popcnt,abm,mmx,avx,avx2,tune=native")
*/

#ifdef LOCAL
    #define dbg(x) cout << #x << " : " << x << endl;
#else
    #define dbg(x)
#endif

#define int long long
#define pb push_back
#define ppb pop_back()
#define mp make_pair
#define fi(a, b) for (int i = a; i < b; i++)
#define fj(a, b) for (int j = a; j < b; j++)
#define fk(a, b) for (int k = a; k < b; k++)
#define fi1(a, b) for (int i = a - 1; i >= b; i--)
#define fj1(a, b) for (int j = a - 1; j >= b; j--)
#define fk1(a, b) for (int k = a - 1; k >= b; k--)
#define fx(x, a) for (auto& x : a)
#define rep(i, a, b) for (int i = a; i < b; ++i)
#define rep1(i, a, b) for (int i = a - 1; i >= b; --i)
#define siz(x) (int)x.size()
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define left leftkekmda
#define right rightkekmda

using namespace std;

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

template<typename T> ostream& operator << (ostream &os, const vector<T> &b) {
    for (auto &k : b) os << k << ' ';
    return os;
}
template<typename T> istream& operator >> (istream &is, vector<T> &b) {
    for (auto &k : b) is >> k;
    return is;
}

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef char ch;
typedef string str;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpii;
typedef vector<vpii> vvpii;
typedef vector<ch> vch;
typedef vector<vch> vvch;
typedef vector<str> vs;

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

const int N = 21;
int a[N];

int32_t main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin >> n;
    fi(0, n) cin >> a[i];

    int ans = 1ll << 31;
    for (int mask = 1; mask < (1 << n); mask += 2) {
        int curb = 0;
        int curx = 0;
        for (int i = 0; i < n; ++i) {
            if ((mask >> i) & 1) {
                curx ^= curb;
                curb = 0;
            }
            curb |= a[i];
        }
        curx ^= curb;
        mine(ans, curx);
    }
    cout << ans << '\n';
}


/*
 * @Author: Luisvacson
 * @LastEditors: Luisvacson
 * @Descriptions: None
 * @Date: 2021-05-01 20:05:46
 * @LastEditTime: 2021-05-01 20:18:58
 * @FilePath: \C++\Practice\B.cpp
 */
#include <bits/stdc++.h>
using namespace std;
#define MAXN 1005

int n, d1, h1;
int d[MAXN], h[MAXN];
signed main() {
    scanf("%d%d%d", &n, &d1, &h1);
    register int i;

    double ans = -1;
    for (i = 1; i <= n; ++i) {
        scanf("%d%d", &d[i], &h[i]);
        int d2 = d[i], h2 = h[i];
        // printf("%d %d\n%d %d\n%d %d\n", h1, h2, d1, d2, h2 - h1, d2 - d1);
        double k = (double)((h2 - h1) * 1.0 / (d2 - d1));
        // printf("%.10lf\n", k);
        double b = h1 - k * d1;
        b = max(b, 0.0);
        ans = max(ans, b);
    }

    printf("%.10lf\n", ans);
    return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <climits>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <queue>

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>(b);i--)
#define pb push_back
#define ff first
#define ss second
#define endl '\n'
#define mp make_pair
#define pb push_back
#define gap " "
#define vi vector<int>
#define ii pair<int,int>
#define vii vector<ii>
#define ldb long double

//memset(dp,-1,sizeof(dp)) sets value to -1 of everything in dp
//vector < vector<int > > vec(n,vector<int>(m,0)) here n are rows(top to down ) and m columns all with m vectors initialised with values 0
//ARRAY OF VECTORS --> vector<int> ar[size] and to pass it in a function we use foo(vector<int>(&ar)[size])
//Number of digits in N =floor(log10(N)) + 1;

typedef long long ll;
using namespace std;

int solve(){
    ldb n,D,H;
    cin>>n>>D>>H;
    ldb r=INT_MIN;
    rep(i,0,n)
    {
        ldb d,h;
        cin>>d>>h;
        r=max(r,(D*h-d*H)/(D-d));
    }
    if(r<0)
    {
        cout<<0.0<<endl;
        return 0;
    }
    cout<<r<<endl;
    return 0;

}
int main(){
#ifndef ONLINE_JUDGE
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
    #endif
ios_base::sync_with_stdio(false);
    cin.tie(NULL);
int t=1;
while(t--){
      solve();
}
return 0;
}


#include<iostream>
#include<vector>
using namespace std;
const int N = 2e5;
int n;
int a[N],c[N];
int main(){
	cin>>n;
	string b;
    cin>>b;
    int minn = 1e9;
  	for(int i=1;i<=n+1;i++)	cin>>a[i], minn=min(minn,a[i]);
  	b = " " + b;

  	int k = -1;
  	for(int i=10000;i>=1;i--){
  	    int now = a[1] / i;
  	    int nxt;
  	    bool fl = true;
  	    for(int j=1;j <= n; j++){
  	        nxt = a[j + 1] / i;
  	        if((b[j]=='<' and now >= nxt)||(b[j]=='>' and now <= nxt)){
  	            fl = false;
  	            break;
  	        }
  	        now = nxt;
  	    }
  	    if(fl){
  	        for(int j=1;j <= n; j++){
  	            now = a[j] / i;
  	            nxt = a[j + 1] / i;
  	            if(b[j]=='<'){
  	                if(a[j]%i>a[j+1]%i and nxt-now<=1) fl = false;
  	            }
  	            else{
  	                if(a[j]%i<a[j+1]%i and now-nxt<=1) fl = false;
  	            }
  	        }
            if(!fl) continue;
  	        k = i;
  	        break;
  	    }
  	}
  	cout<<k<<'\n';
  	for(int i=1;i<=n+1;i++)   c[i] = a[i]%k;

  	for(int i=1;i<=k;i++){
  	    for(int j=1;j<=n+1;j++){
  	        if(c[j]){cout<<a[j]/k+1<<' ';    c[j]--;}
  	        else     cout<<a[j]/k<<' ';
  	    }
  	    puts("");
  	}

	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#ifdef __DEBUG__
    void debug_out() { cerr << endl; }
    template <typename Head, typename... Tail>
    void debug_out(Head H, Tail... T) {cerr << " " << H; debug_out(T...);}
    #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
    #define debug(...)
#endif

using ll = long long int;
inline void fast_io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); };
template<typename T, typename S> inline ostream& operator<<(ostream& os, const map<T, S> p) { for (auto el : p) cout << "[" << el.first << ";" << el.second << "]"; return os; }
template<typename T> inline ostream& operator<<(ostream& os, const vector<T>& v) { for (auto el : v) cout << el << " "; return os; }
template<typename T> inline vector<T> fetch_vec(int sz) { vector<T> ret(sz); for (auto& elem : ret) cin >> elem; return ret; }

ll N,X;
vector<ll> A;
vector<ll> coff_max;
vector<ll> coff_x;

inline void input(){
    fast_io();
    cin >> N >> X;
    A = fetch_vec<ll>(N);
}

void kuriagari(vector<ll> &y){
    int n = y.size();
    for (int i = 0; i < n-1; i++)
    {
        if(y[i]==coff_max[i]){
            y[i] = 0;
            y[i+1]++;
        }
    }
}

int tlesolve(){
    coff_x.assign(N,0);
    coff_max.assign(N,0);
    // vector<ll> coff_max.assin(N,0);
    coff_max[N-1] = 100;
    for (int i = 0; i < N-1; i++)
    {
        coff_max[i] = A[i+1]/A[i];
    }

    for (int i = N-1; i >= 0; i--)
    {
        coff_x[i] = X/A[i];
        X %= A[i];
    }

    vector<vector<ll>> ys;
    ys.push_back(coff_x);
    for (int i = 0; i < N; i++)
    {
        vector<vector<ll>> tmp = ys;
        for(auto y:ys){
            if(y[i]!=0 && i!=N-1){
                vector<ll> ny = y;
                ny[i] = 0;
                ny[i+1]++;
                kuriagari(ny);
                tmp.push_back(ny);
            }
        }
        ys = tmp;
    }
    cout << ys.size() << endl;
    debug(coff_x);
    debug(coff_max);
    sort(ys.begin(),ys.end());
    debug(ys);
    return 0;
}

int solve(){
    coff_x.assign(N,0);
    coff_max.assign(N,0);
    // vector<ll> coff_max.assin(N,0);
    for (int i = 0; i < N-1; i++)
    {
        coff_max[i] = A[i+1]/A[i];
    }
    ll Y = X;
    for (int i = N-1; i >= 0; i--)
    {
        coff_x[i] = X/A[i];
        Y %= A[i];
    }
    coff_max[N-1] = coff_x[N-1]+2;
    debug(coff_x);
    debug(coff_max);

    vector<map<ll,ll>> dp(N+1);
    dp[N][X] = 1;
    for (int i = N-1; i >= 0; i--)
    {
        for(auto [d,c]:dp[i+1]){
            // for (int x = -coff_max[i]+1; x < coff_max[i]; x++)
            // {
            //     if(abs(d-x*A[i]) < A[i]) dp[i][d-x*A[i]] += c;
            // }
            if(d > 0){
                ll x = d/A[i];
                if(x < coff_max[i]){
                    dp[i][d-x*A[i]] += c;
                }
                if(x+1 < coff_max[i]){
                    dp[i][d-(x+1)*A[i]] += c;
                }
            }
            else if(d < 0){
                ll x = abs(d)/A[i];
                if(abs(x) < coff_max[i]){
                    dp[i][d+x*A[i]] += c;
                }
                if(abs(x+1) < coff_max[i]){
                    dp[i][d+(x+1)*A[i]] += c;
                }
            }
            else{
                dp[i][d] += c;
            }
        }
    }
    debug(dp);
    cout << dp[0][0] << endl;
    return 0;
}

int main()
{
    input();
    solve();
    return 0;
}


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

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define fo(i,n) for(int i=0;i<n;i++)
#define fos(i,n) for(ll i=0,i<n;i++)
#define loop(i,a,b) for (int i = a; i < b; i++)
#define loops(i,a,b) for (ll i = a; i < b; i++)

void solve(){
    string s;
    cin>>s;

    reverse(s.begin(),s.end());

    loop(i,0,s.size()){
        if(s[i]=='6'){
            s[i]='9';
        }else if(s[i]=='9'){
            s[i]='6';
        }
    }

    cout<<s<<"\n";
}

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

    solve();

	return 0;
}

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

int main()
{

        long long n,m,a,b,c,d,e,f,g,h,p,q,r,fr,sc,tr,sz=0,tz,i,j,k,mx=LLONG_MIN,mn=LLONG_MAX;
        long long x=0,y=0,cnt=0,res=0,ans=0,sum=0; long long flg=0,flag=1,na=0,as=1;
        vector<long long>u,v,w; vector< pair<long long,long long> >vct; vector<string>vst;
        set<long long>st,nt,tt; map<long long,long long>mp,nq,qr; string str,ttr,ntr;

        //scanf("%lld",&n);

        cin>>str; sz=str.size();  char ch; reverse(str.begin(),str.end());

        for(i=0;i<sz;i++)
        {
            ch=str[i];

            if(ch=='6')ch='9';
            else if(ch=='9')ch='6';

            cout<<ch;
        }

        cout<<endl;

   return 0;

}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<long long> enum_divisors(long long N) {
    vector<long long> res;
    for (long long i = 1; i * i <= N; ++i) {
        if (N % i == 0) {
            res.push_back(i);
            // 重複しないならば i の相方である N/i も push
            if (N/i != i) res.push_back(N/i);
        }
    }

    return res;
}

int main() {
    long long S, P;
    cin >> S >> P;
    const auto &res = enum_divisors(P);
    for (int i = 0; i < res.size(); ++i) {
        long long N = res[i];
        long long M = P / N;

        if(N + M == S) {
            cout << "Yes" << endl;
            return 0;
        }
    }

    cout << "No" << endl;
}

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

#define ll long long
#define pll pair<ll,ll>
#define ff first
#define ss second
#define pb push_back
#define endl "\n"
const ll maxn =6e5+10;
const ll mod=1e9+7;
const ll base=1e18;

ll cnt[maxn];
ll f[maxn];

ll get_duong(ll a,ll b)
{
    if (b<0) return 0;
    ll kc=b/2;
    ll ans=0;
    if (a<=kc)
    {
        ans=ans+2*a+1;
    }
    else
    {
        ans=ans+kc+1;
        ll cl=b-kc*2;
        if (cl>=1)
        {
            ans=ans+kc+1;
        }
        else
        {
            ans=ans+kc;
        }
    }
    return ans;
}
ll get_am(ll a,ll b)
{
    if (b<=0) return 0;
    ll kc=b/2;
    ll ans=2*kc;
    if (b%2==0)
        ans--;
    return ans;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    if (fopen("t.inp","r"))
    {
        freopen("test.inp","r",stdin);
        freopen("test.out","w",stdout);
    }
    ll a, b;
    cin>> a>> b;

    if (a==0)
    {
        ll ans=get_am(a,b)+1;
        cout <<ans<<endl;
    }
    else if (a>0)
    {
        ll ans=get_duong(a,b)+get_am(a,b-1);
        cout <<ans<<endl;
    }
    else
    {
        ll ans=get_am(a,b)+get_duong(-a,b-1);
        cout <<ans<<endl;
    }

}


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

// 総数を1000000007（素数）で割った余り
const long long mod = 1e9 + 7;

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define ull unsigned long long
#define ld long double
#define vi vector<int>
#define vll vector<ll>
#define vc vector<char>
#define vs vector<string>
#define vpii vector<pii>
#define vpll vector<pll>
#define Graph vector<vector<int>>

#define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; i++)
#define rep1(i, n) for (int i = 1, i##_len = (n); i <= i##_len; i++)
#define repr(i, n) for (int i = ((int)(n)-1); i >= 0; i--)
#define rep1r(i, n) for (int i = ((int)(n)); i >= 1; i--)

#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

#define SORT(v, n) sort(v, v + n);
#define VSORT(v) sort(v.begin(), v.end());
#define RSORT(x) sort(rall(x));
#define pb push_back
#define mp make_pair

#define INF (1e9)
#define PI (acos(-1))
#define EPS (1e-7)

ull gcd(ull a, ull b) { return b ? gcd(b, a % b) : a; }
ull lcm(ull a, ull b) { return a / gcd(a, b) * b; }

const string YES = "Yes";
const string NO = "No";

int main() {
    long long A;
    scanf("%lld", &A);
    long long B;
    scanf("%lld", &B);
    long long C;
    scanf("%lld", &C);
    long long D;
    scanf("%lld", &D);

    ll sum = A + B + C + D;
    ll ab = A + B;
    ll ac = A + C;
    ll ad = A + D;
    ll bc = B + C;
    ll bd = B + D;
    ll cd = C + D;

    if ((2 * ab == sum) || (2 * ac == sum) || (2 * ad == sum) ||
        (2 * A == sum) || (2 * B == sum) || (2 * C == sum) || (2 * D == sum)) {
        cout << "Yes" << endl;
    }

    else {
        cout << "No" << endl;
    }

    return 0;
}

/* in the name of Anton */

/*
  Compete against Yourself.
  Author - Aryan (@aryanc403)
  Atcoder library - https://atcoder.github.io/ac-library/production/document_en/
*/

#ifdef ARYANC403
    #include <header.h>
#else
    #pragma GCC optimize ("Ofast")
    #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
    #pragma GCC optimize ("-ffloat-store")
    #include<bits/stdc++.h>
    #define dbg(args...) 42;
#endif

using namespace std;
#define fo(i,n)   for(i=0;i<(n);++i)
#define repA(i,j,n)   for(i=(j);i<=(n);++i)
#define repD(i,j,n)   for(i=(j);i>=(n);--i)
#define all(x) begin(x), end(x)
#define sz(x) ((lli)(x).size())
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define endl "\n"

typedef long long int lli;
typedef long double mytype;
typedef pair<lli,lli> ii;
typedef vector<ii> vii;
typedef vector<lli> vi;

const auto start_time = std::chrono::high_resolution_clock::now();
void aryanc403()
{
#ifdef ARYANC403
auto end_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end_time-start_time;
    cerr<<"Time Taken : "<<diff.count()<<"\n";
#endif
}

const lli INF = 0xFFFFFFFFFFFFFFFL;

lli seed;
mt19937 rng(seed=chrono::steady_clock::now().time_since_epoch().count());
inline lli rnd(lli l=0,lli r=INF)
{return uniform_int_distribution<lli>(l,r)(rng);}

class CMP
{public:
bool operator()(ii a , ii b) //For min priority_queue .
{    return ! ( a.X < b.X || ( a.X==b.X && a.Y <= b.Y ));   }};

void add( map<lli,lli> &m, lli x,lli cnt=1)
{
    auto jt=m.find(x);
    if(jt==m.end())         m.insert({x,cnt});
    else                    jt->Y+=cnt;
}

void del( map<lli,lli> &m, lli x,lli cnt=1)
{
    auto jt=m.find(x);
    if(jt->Y<=cnt)            m.erase(jt);
    else                      jt->Y-=cnt;
}

bool cmp(const ii &a,const ii &b)
{
    return a.X<b.X||(a.X==b.X&&a.Y<b.Y);
}

const lli mod = 1000000007L;
// const lli maxN = 1000000007L;

    lli T,n,i,j,k,in,cnt,l,r,u,v,x,y;
    lli m;
    string s;
    vi a;
    //priority_queue < ii , vector < ii > , CMP > pq;// min priority_queue .

int main(void) {
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    // freopen("txt.in", "r", stdin);
    // freopen("txt.out", "w", stdout);
// cout<<std::fixed<<std::setprecision(35);
// cin>>T;while(T--)
{

    n=4;
    a.clear();a.reserve(n);

    fo(i,n)
    {
        cin>>in;
        a.pb(in);
    }

    for(lli msk=1;msk<(1LL<<n);++msk){
        lli sum=0;
        fo(i,n){
            if(msk&(1LL<<i))
                sum+=a[i];
            else
                sum-=a[i];
        }
        if(sum==0){
            cout<<"Yes"<<endl;
            return 0;
        }
    }
    cout<<"No"<<endl;
}   aryanc403();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int sz = 2e5+5;

typedef pair <int,int> pii;
#define x first
#define y second

int csub[sz], dp[sz];
vector <int> g[sz];

void dfs(int u) {
   csub[u] = dp[u] = 1;
   vector <pii> od, ev;
   for(int v : g[u]) {
      dfs(v);
      csub[u] += csub[v];
      if(csub[v] & 1) od.emplace_back(csub[v] - 2 * dp[v], v);
      else ev.emplace_back(csub[v] - 2 * dp[v], v);
   }
   sort(od.begin(), od.end(), greater<pii>());
   sort(ev.begin(), ev.end(), greater<pii>());
   int ei = 0, oi = 0;
   for(; ei<ev.size(); ei++) {
      auto v = ev[ei].y;
      if(csub[v] - dp[v] > dp[v]) dp[u] += dp[v];
      else break;
   }
   for(; oi<od.size(); oi++) {
      auto v = od[oi].y;
      if(oi & 1) dp[u] += csub[v] - dp[v];
      else dp[u] += dp[v];
   }
   for(; ei<ev.size(); ei++) {
      auto v = ev[ei].y;
      if(oi & 1) dp[u] += csub[v] - dp[v];
      else dp[u] += dp[v];
   }
}

int main() {
   int n;
   cin >> n;
   for(int i=2; i<=n; i++) {
      int j;
      scanf("%d", &j);
      g[j].push_back(i);
   }
   dfs(1);
   cout << dp[1];
}

#include<algorithm>
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int N;
int X[200][3],Ans[200][4];
int G2[10000][10000];
vector<vector<int>>G(10001);
vector<vector<int>>X_vec;

int scoring(vector<vector<int>>&ans){
    double ref=0;
    for(int i=0;i<N;++i){
        if(ans[i][0]<=X[i][0] && X[i][0]<ans[i][2] && ans[i][1]<=X[i][1] && X[i][1]<ans[i][3]){
            int S=(ans[i][2]-ans[i][0])*(ans[i][3]-ans[i][1]);
            ref+=1.0-powf(1.0-(double)min(X[i][2],S)/(double)max(X[i][2],S),2);
        }
    }
    ref/=(double)N;
    return (int)(1000000000*ref);
}

bool overlap(int id,int a,int b,int c,int d){
    for(int i=0;i<N;++i)if(i!=id){
        int x1=Ans[i][0];
        int y1=Ans[i][1];
        int x2=Ans[i][2];
        int y2=Ans[i][3];
        if(max(a,x1)<min(x2,c) && max(b,y1)<min(y2,d)){
            //cout<<"over "<<a<<" "<<x2<<" "<<b<<" "<<y2<<" "<<c<<" "<<x1<<" "<<d<<" "<<y1<<endl;
            return true;
        }
    }
    return false;
}

void greedy(){
    int a,b,c,d,id;
    //面積でソート
    //{id,x,y,r}
    sort(X_vec.rbegin(),X_vec.rend(),[](const vector<int>&a,const vector<int>&b){return a[3]<b[3];});
    //初期解の生成
    for(int n=0;n<N;++n){
        id=X_vec[n][0];
        a=X_vec[n][1];
        b=X_vec[n][2];
        c=a+1;
        d=b+1;
        //答えを記録
        Ans[id][0]=a;
        Ans[id][1]=b;
        Ans[id][2]=c;
        Ans[id][3]=d;
    }

    //どこまで広げられるか見ていく
    for(int n=0;n<N;++n){
        id=X_vec[n][0];
        a=Ans[id][0];
        b=Ans[id][1];
        c=Ans[id][2];
        d=Ans[id][3];

        //右斜め上方向に伸ばす
        int c1=c;
        int b1=b;
        while(!overlap(id,a,b1,c1,d) && c1<10000 && b1>0){
            --b1;
            ++c1;
        }
        //cout<<"1: "<<b<<" "<<b1<<" "<<c<<" "<<c1<<endl;

        //右斜め下方向に伸ばす
        int c2=c;
        int d1=d;
        while(!overlap(id,a,b,c2,d1) && c1<10000 && d1<10000){
            ++c1;
            ++d1;
        }
        if(c!=c1)--c1;
        if(d!=d1)--d1;
        //cout<<"2: "<<c<<" "<<c2<<" "<<d<<" "<<d1<<endl;

        //左斜め上方向に伸ばす
        int a1=a;
        int b2=b;
        while(!overlap(id,a1,b2,c,d) && a1>0 && b2>0){
            --a1;
            --b2;
        }
        if(a!=a1)++a1;
        if(b!=b2)++b2;
        //cout<<"3: "<<a<<" "<<a1<<" "<<b<<" "<<b2<<endl;

        //左斜め下方向に伸ばす
        int a2=a;
        int d2=d;
        while(!overlap(id,a2,b,c,d2) && a2>0 && d2<10000){
            --a2;
            ++d2;
        }
        if(a!=a2)++a2;
        if(d!=d2)--d2;
        //cout<<"4: "<<a<<" "<<a2<<" "<<d<<" "<<d2<<endl;
        //cout<<a1<<" "<<a2<<" "<<b1<<" "<<b2<<" "<<c1<<" "<<c2<<" "<<d1<<" "<<d2<<endl;

        a=max(a1,a2);
        b=max(b1,b2);
        c=min(c1,c2);
        d=min(d1,d2);
        //答えを記録
        Ans[id][0]=a;
        Ans[id][1]=b;
        Ans[id][2]=c;
        Ans[id][3]=d;
    }
}

int main(){
    //入力
    cin>>N;
    int x,y,r;
    for(int i=0;i<N;++i){
        cin>>X[i][0]>>X[i][1]>>X[i][2];
        X_vec.push_back({i,X[i][0],X[i][1],X[i][2]});
        G[X[i][0]].push_back(X[i][1]);
        G2[X[i][0]][X[i][1]]=1;
    }
    for(int i=0;i<N;++i)sort(G[i].begin(),G[i].end());
    //アイディア
    //希望する点の座標を隣接リストで保持する
    //for debug
    //for(int i=0;i<n;++i)cout<<X_vec[i][3]<<endl;
    greedy();

    //出力
    for(int i=0;i<N;++i)cout<<Ans[i][0]<<" "<<Ans[i][1]<<" "<<Ans[i][2]<<" "<<Ans[i][3]<<endl;
}


#include<bits/stdc++.h>
#define haiyaku ios::sync_with_stdio(false), cin.tie(NULL);
#define PB push_back
#define F first
#define S second
#define mp make_pair
#define all(x) x.begin(), x.end()
#define int long long
//#define double long double

const int MINI = -2147483647;
const int MAXI = 2147483647;
const long long MAXLL = 9223372036854775807ll / 4;
const long long MINLL = -9223372036854775807ll / 4;

using namespace std;

using pii = pair<int, int>;
using pll = pair<long long, long long>;

bitset<50001> dp;

signed main () {
  ios::sync_with_stdio(false), cin.tie(NULL);

  int N; cin >> N;
  vector<int> t(N);
  for(int &X : t) cin >> X;

  dp[0] = true;
  int sum = accumulate(all(t), 0ll);
  for(int V : t) {
    for(int i = sum / 2; i >= V; i--)
      if (dp[i - V]) dp[i] = true;
  }

  for(int i = sum / 2; i >= 0; i--) {
    if (dp[i]) {
      cout << sum - i << '\n';
      return 0;
    }
  }

  return 0;
}

#include<bits/stdc++.h>
typedef long long ll;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define pb push_back
#define  lsb(x) ((x) & (-x))
#define  PI acos(-1)
#define  line cout << endl;
#define  getbit(n, i) (((n) & (1LL << (i))) != 0)
#define  resetbit(n, i) ((n) & (~(1LL << (i))))
#define  setbit(n, i) ((n) | (1LL << (i)))
#define  togglebit(n, i) ((n) ^ (1LL << (i)))
const ll mod = (ll) 1e9+7;
using namespace std;

int32_t main() {
  IOS
  #ifdef gm
  freopen("int.txt", "r", stdin);
  #endif
 int  n;
 cin >> n;

int sum = 0;

bitset<100005 >dp;
dp[0] =1;

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

int f;
cin >> f;
sum += f;
dp |= dp << f;

}

int res= sum;

for(int i=0;i< sum+1 ;i++)
{
    if(dp[i])
      res = min(res, max(i, sum - i));

}

cout << res << endl;
 return 0;
  }


#include <bits/stdc++.h>

using namespace std;
using ll = long long int;

void tc(){

    int n;
    cin >> n;

    string s;
    cin >> s;

    int ans = 0;

    for (int i=0; i<n; i++){
        int a = 0, t = 0, c = 0, g = 0;
        for (int j=i; j<n; j++){
            if (s[j] == 'A') a++;
            if (s[j] == 'T') t++;
            if (s[j] == 'G') g++;
            if (s[j] == 'C') c++;

            if (a == t and g == c) ans++;
        }
    }

    cout << ans << endl;

}

int main(){

    int t = 1;
    while(t--) tc();

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(x) (x).begin(),(x).end()
#define SIZE(x) ((ll)(x).size())
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define INF 1e9
typedef long long ll;
typedef long double ld;

int main(){
  ll n;
  string s;
  cin>>n>>s;
  vector<vector<ll>> v(n+1,vector<ll> (4));
  vector<char> w={'A','T','C','G'};
  REP(i,n){
    REP(j,4)if(s[i]==w[j])v[i+1][j]++;
  }
  ll cnt=0;
  FOR(i,1,n+1){
    REP(j,4){
      v[i][j]+=v[i-1][j];
    }
  }
  REP(i,n){
    FOR(j,i+1,n+1){
      ll a=v[j][0]-v[i][0], t=v[j][1]-v[i][1], c=v[j][2]-v[i][2], g=v[j][3]-v[i][3];
      if(a==t&&c==g)cnt++;
    }
  }
  cout<< cnt <<endl;
  return 0;

}


/*
“The only way that we can live is if we grow.
 The only way we can grow is if we change.
The only way we can change is if we learn.
 The only way we can learn is if we are exposed.
 And the only way that we are exposed is if we throw ourselves into the open.”
 ***************************************   ************************   **********************************
*/
#include <bits/stdc++.h>
using namespace std;

#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
using namespace __gnu_pbds;

typedef tree<int, null_type, less_equal<int>, rb_tree_tag,
             tree_order_statistics_node_update> data_set;
#define fbo find_by_order
#define ook order_of_key

//---------------------mishra ka idea------------------
#define int         long long
#define double      long double
#define pb          push_back
#define pf          push_front
#define pii         pair<int,int>
#define vi          vector<int>
#define vii         vector<pii>
#define all(a)      (a).begin(),(a).end()
#define rall(a)     (a).rbegin(),(a).rend()
#define x           first
#define y           second
#define endl        '\n'
#define sz(x)     (int)(x).size()
#define ull       unsigned long long
//------------------------mishra ka idea-------------------

//-------------------------alsi hu mai-----------------------
#define fo(i,l,u)   for(i=l;i<u;i++)
#define rfo(i,l,u)  for(i=l;i>=u;i--)
#define allfo(s)    for(auto it=(s).begin();it!=(s).end();it++)
#define _init(b)     memset(b,-1,sizeof(b))
#define _init0(b)     memset(b,0,sizeof(b))
#define MOD         1000000007
#define hell        998244353
#define output(x) cout << (x ? "YES" : "NO")<<endl;
#define Output(x) cout << (x ? "Yes" : "No")<<endl;
//-------------------------alsi hu mai-----------------------

//--------------------het se uthaya---------------------
#define MOD2 (998244353)
#define MOD3 (1000000009)
#define PI acos(-1)
#define eps (1e-8)
#define INF (1e18)

template<class A,class B>ostream&operator<<(ostream&out,const pair<A,B>&a){return out<<"("<<a.first<<","<<a.second<<")";}
template<class A>ostream&operator<<(ostream&out,const vector<A>&a){for(const A &it:a)out<<it<<" ";return out;}
template<class A,class B>istream&operator>>(istream&in,pair<A,B>&a){return in>>a.first>>a.second;}
template<class A>istream&operator>>(istream&in,vector<A>&a){for(A &i:a)in>>i;return in;}
ifstream cinn("in.txt");ofstream coutt("out.txt");
int poww(const int &a,int b,const int &m=MOD){if(b==0)return 1;int x=poww(a,b/2,m);x=x*x%m;if(b&1)x=x*a%m;return x;}

//--------------------het se uthaya-------------------------------------------------------------------

int gcd(int a, int b) {if(a>b)swap(a,b) ;  if (a == 0)  return b; return gcd(b % a, a); }
int rint(int  l , int r){return rand()%(r-l+1) + l ;}

//---------------------------aab code dekho bahut template dekh liya---------------------------------

signed main()
{
   //freopen("input.txt", "r", stdin);
   //freopen("output.txt", "w", stdout);
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
   int i,j,x,t,n;
   cin>>n;
   string s;
   cin>>s;
   //int n = s.length();
   int pref[n+1] , pref1[n+1];
   pref[0]=0;
   pref1[0]=0;
   int c1 = 0 , c2 = 0;
   fo(i,0,n){
    if(s[i]=='A'){
      c1++;
    }
    if(s[i]=='T'){
      c1--;
    }
    if(s[i]=='G'){
      c2++;

    }
    if(s[i]=='C'){
      c2--;
    }
    pref[i+1]=c1;
    pref1[i+1]=c2;
   }
   int ans = 0;
   fo(i,1,n+1){
   // cout<<pref[i]<<" "<<pref1[i]<<"<<<"<<endl;
    fo(j,i+1,n+1){

    //  cout<<pref[j]-pref[i-1]<<" "<<pref1[j]-pref1[i-1]<<endl;
      if((pref[j]-pref[i-1]==0 )&& (pref1[j]-pref1[i-1]==0))ans++;
    }
   }
   cout<<ans<<endl;

    return 0;
}

//----------------abc tez kar liya iska matlab ye nahi tum legend ho kya pata hagdo aage ------------------

using namespace std;

#define visual

#ifdef visual
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <assert.h>
#include <functional>
#include <math.h>
#include <string>
#include <ctime>
#endif
#ifndef visual
#include <bits/stdc++.h>
#endif

typedef long long ll;

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

    map<pair<int, int>, int> m;
    int x = 0;
    int y = 0;
    int n;
    string s;
    cin >> n >> s;
    ll ans = 0;
    m[{0, 0}] = 1;
    for (char c : s) {
        if (c == 'C') x--;
        if (c == 'G') x++;
        if (c == 'A') y--;
        if (c == 'T') y++;
        ans += m[{x, y}];
        m[{x, y}]++;
    }

    cout << ans << endl;

}


#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rrep(i, n) for(int i = 1; i <= (int)(n); i++)
#define drep(i, n) for(int i = (n)-1; i >= 0; i--)
#define ALL(x) (x).begin(), (x).end()
#define dup(x,y) (((x)+(y)-1)/(y))
#define srep(i,s,t) for (int i = s; i < t; ++i)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
const ll LINF = 1001002003004005006ll;
const int INF = 1001001001;
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 int mod = 1000000007;
// const int mod = 998244353;

string s;
int n;
int ans = INF;

bool is3(string t) {
  int now = 0;
  rep(i, t.size()) now += t[i] - '0';
  return now%3 == 0;
}

void func(string t, int i) {
  if (i == n) {
    if (is3(t)) ans = min(ans, n - (int)t.size());
    return;
  }
  func(t+s[i], i+1);
  func(t, i+1);
}

int main() {
  cin >> s;
  n = s.size();
  string t = "";
  func(t, 0);
  if (ans >= n) ans =-1;
  cout << ans << endl;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define P pair<ll,ll>
#define FOR(I,A,B) for(ll I = ll(A); I < ll(B); ++I)
#define FORR(I,A,B) for(ll I = ll((B)-1); I >= ll(A); --I)
#define TO(x,t,f) ((x)?(t):(f))
#define SORT(x) (sort(x.begin(),x.end())) // 0 2 2 3 4 5 8 9
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin()) //xi>=v  x is sorted
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin()) //xi>v  x is sorted
#define NUM(x,v) (POSU(x,v)-POSL(x,v))  //x is sorted
#define REV(x) (reverse(x.begin(),x.end())) //reverse
ll gcd_(ll a,ll b){if(a%b==0)return b;return gcd_(b,a%b);}
ll lcm_(ll a,ll b){ll c=gcd_(a,b);return ((a/c)*b);}
#define NEXTP(x) next_permutation(x.begin(),x.end())
const ll INF=ll(1e16)+ll(7);
const ll MOD=1000000007LL;
#define out(a) cout<<fixed<<setprecision((a))
//tie(a,b,c) = make_tuple(10,9,87);
#define pop_(a) __builtin_popcount((a))
ll keta(ll a){ll r=0;while(a){a/=10;r++;}return r;}

int main(){

	ll N;
	cin >> N;
	vector<ll> X(N),Y(N),Z(N);
	FOR(i,0,N) cin >> X[i] >> Y[i] >> Z[i];

	ll dp[1LL<<N][N];
	FOR(i,0,(1<<N))FOR(j,0,N){
		dp[i][j] = INF;
	}
	dp[0][0] = 0;

	FOR(s,0,(1<<N)){
		FOR(j,0,N){//now
			FOR(k,0,N){//to
				ll c = abs(X[j]-X[k])+abs(Y[j]-Y[k])+max(0LL,Z[k]-Z[j]);
				dp[s|(1<<k)][k] = min( dp[s|(1<<k)][k] , dp[s][j]+c );
			}
		}
	}

	cout << dp[(1<<N)-1][0] << endl;

}


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

// Reused : hackerearth.com/submission/48716644/

const int N = 5e5+5;
int t, n, m;
int arr[N], bit[N] = {};

void update(int i, int val) {
    for( ; i <= m; i += (i&-i) ) {
        bit[i] += val;
    }
}

int get(int i) {
    int res = 0;
    for( ; i; i -= (i&-i) ) {
        res += bit[i];
    }
    return res;
}

void clear() {
    memset(bit, 0, sizeof(bit));
}

int main() {
    t=1;
    while(t--) {
        scanf("%d", &n);

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

        clear();
        ll tot = 0;
        int rem[N], add[N];
        for( int i = n-1; i >= 0; i-- ) {
            rem[i] = get(arr[i]-1);
            add[i] = n-i-1-get(arr[i]);
            tot += 1LL*rem[i];
            update(arr[i], 1);
        }

        clear();
        ll res = tot;
        cout<<tot<<endl;
        for( int i = 0; i < n-1; i++ ) {
            int r = get(arr[i]-1);
            int a = i-get(arr[i]);
            tot += 1LL*(a-r+add[i]-rem[i]);
            cout<<tot<<endl;
            res ^= tot;
//          cout<<add[i]<<" "<<rem[i]<<" "<<tot<<endl;;
            update(arr[i], 1);
        }
    }

    return 0;
}

#pragma GCC optimize("O2")

#include <bits/stdc++.h>

namespace IN {
#define BUF_SIZE 1 << 17
static char buf[BUF_SIZE], *fs = buf, *ft = buf;
inline int nc() { return fs == ft && (ft = (fs = buf) + fread(buf, 1, BUF_SIZE, stdin), fs == ft) ? EOF : *fs++; }
template <typename T>
inline int rn(T &x) {
    x = 0;
    int f = 0;
    char ch = nc();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = 1;
        ch = nc();
        if (ch == EOF) return EOF;
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - 48;
        ch = nc();
    }
    x = f ? -x : x;
    return 0;
}
template <typename T>
inline int read(T &x) {
    return rn(x);
}
template <typename T, typename... Args>
inline int read(T &x, Args &...args) {
    rn(x);
    return read(args...);
}
#undef BUF_SIZE
}  // namespace IN

using namespace IN;
using namespace std;

#define SIZE 300010
#define HINF 0x3f3f3f3f
#define LL long long
#define PLL pair<LL, LL>
#define PII pair<int, int>
#define MP make_pair
#define FI first
#define SE second
#define PB push_back
#define ALL(A) A.begin(), A.end()
#define LOWBIT(x) (x & (-x))
#define BPQ(type, name) priority_queue<type> name
#define SPQ(type, name) priority_queue<type, vector<type>, greater<type>> name
#define REP(i, n) for (LL i = 0; i < (LL)n; ++i)
#define REP1(i, n) for (LL i = 1; i <= (LL)n; ++i)
#define REP_R(i, a, b) for (LL i = (LL)a; i < (LL)b; ++i)
#define REP_RR(i, a, b) for (LL i = (LL)a; i >= (LL)b; --i)
#define SETVAL(array, val) memset(array, val, sizeof(array))
// Graph
typedef struct {
    LL w;
} E_elem;
#define GRAPH(name, vertex_sz, edge_sz) \
    struct {                            \
        int VERTEX, NEXT;               \
        E_elem ELEM;                    \
    } name##_E[edge_sz];                \
    int name##_H[vertex_sz];            \
    int name##_EDGE_NUM = 0
#define ADD_EDGE(name, u, v, elem)                    \
    do {                                              \
        name##_E[++name##_EDGE_NUM].VERTEX = v;       \
        name##_E[name##_EDGE_NUM].ELEM = elem;        \
        name##_E[name##_EDGE_NUM].NEXT = name##_H[u]; \
        name##_H[u] = name##_EDGE_NUM;                \
    } while (0)
#define FE_V(name, v) for (int name##_EN = name##_H[v]; name##_EN; name##_EN = name##_E[name##_EN].NEXT)
#define CURR_EN(name) name##_EN
#define REV_EN(name) (name##_EN ^ 1)
#define CURR_V(name) name##_E[name##_EN].VERTEX
#define CURR_ELEM(name) name##_E[name##_EN].ELEM
// Debug
#define DISP(arr, n)                 \
    REP(i, n) printf("%d ", arr[i]); \
    cout << endl;
#define DISP1(arr, n)                 \
    REP1(i, n) printf("%d ", arr[i]); \
    cout << endl;
#define DISP_TD(arr, n, m)                  \
    REP(i, n) {                             \
        REP(j, m) printf("%d ", arr[n][m]); \
        printf("\n");                       \
    }
#define DISP_TD1(arr, n, m)                  \
    REP1(i, n) {                             \
        REP1(j, m) printf("%d ", arr[n][m]); \
        printf("\n");                        \
    }

LL n;
LL a[SIZE];
LL b[SIZE];
LL c[SIZE];
LL get(LL x, LL *arr) {
    LL ans = 0;
    for (; x; x -= LOWBIT(x)) ans += arr[x];
    return ans;
}
void add(LL x, LL y, LL *arr) {
    for (; x <= n; x += LOWBIT(x)) arr[x] += y;
}

int main() {
    read(n);
    REP(i, n) read(a[i]), a[i] += 1;
    LL ans = 0;
    vector<LL> v;
    REP_RR(i, n - 1, 0) {
        add(a[i], 1, b);
        LL x = get(a[i] - 1, b);
        ans += x;
        v.PB(x);
    }
    vector<LL> v1;
    REP(i, n) {
        add(a[i], 1, c);
        LL x = get(a[i] - 1, c);
        v1.PB(x);
    }
    REP(i, n) {
        cout << ans << endl;
        ans += n - 1 - 2 * v[n - i - 1] - 2 * v1[i];
    }
    return 0;
}


#include<bits/stdc++.h>
// #include<iostream>
// #include<algorithm>
// #include<vector>
// #include<set>
// #include<queue>
// #include<map>
using namespace std;

#define ll long long
#define ld long double

#define For(n) for(ll i=0;i<n;i++)
#define Forr(a,b) for(ll i=a;i<b;i++)

#define sortt(x) sort(x.begin(),x.end())
#define rsortt(x) sort(x.rbegin(),x.rend())
#define condsortt(x) sort(x.begin(),x.end(),sortBy)

#define MOD 1000000007
#define en "\n"

#define F first
#define S second

#define input(x,n) for(ll i=0;i<n;i++) cin>>x[i]
#define v(A,n) vector<ll> A(n)
#define vi(x) vector<ll> x
#define pb(x) push_back(x)
#define MP make_pair
#define PI 3.14159265

void print(vector<ll> vec)
{
    for(auto itr:vec)
        cout<<itr<<" ";
    cout<<en;
}

void solve()
{
    ll n;
    cin>>n;
    v(A,n);
    input(A,n);
    vector<ll> vec[n+1];
    For(n)
    {
        ll a;cin>>a;
        vec[a].pb(i);
    }
    v(mp,n);
    For(n)
    {
        ll a;cin>>a;
        mp[a-1]++;
    }
    ll ans = 0;
    map<ll,ll> kk;
    For(n)
    {
        ll ch = A[i];
        if(kk.find(ch)!=kk.end())
        {
            ans+=kk[ch];
            continue;
        }
        int zz=0;
        for(auto j:vec[ch])
        {
            zz+=mp[j];
        }
        ans+=zz;
        kk[ch]=zz;
    }
    cout<<ans<<en;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll t=1;
    // cin>>t;
    for(ll i=1;i<=t;i++)
    {
        // cout<<"Case #"<<i<<": ";
        solve();
    }
    return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define mod 1000000007
#define pdd pair<double,double>
#define pii pair<ll,ll>
#define fi first
#define sec second
#define MAXN 1000000000000000005
#define N 300005
#define lgn 20

using namespace std;

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template <typename Arg1>
    void __f(const char* name, Arg1&& arg1){
        cout << name << " : " << arg1 << std::endl;
        //use cerr if u want to display at the bottom
    }
    template <typename Arg1, typename... Args>
    void __f(const char* names, Arg1&& arg1, Args&&... args){
        const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
    }
#else
#define trace(...)
#endif

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

	#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
	#endif
    //Type Your Code Here

   	ll n;
    pair<ll,pii> apx[100000];
    cin>>n;
    for(ll i=0;i<n;i++) {
        ll a,p,x;
        cin>>a>>p>>x;
        apx[i] = {p,{a,x}};
    }
    sort(apx,apx+n);
    ll ans = -1;
    for(ll i=0;i<n;i++) {
        ll a,p,x;
        a = apx[i].sec.fi;
        p = apx[i].fi;
        x = apx[i].sec.sec;
        if(a<x) {
            ans = p;
            break;
        }
    }
    cout<<ans;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define FOR(i,s,n) for(int i = (s); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) for(int i = (n); i >= 0; i--)
#define ALL(n) (n).begin(), (n).end()
#define RALL(n) (n).rbegin(), (n).rend()
#define ATYN(n) cout << ( (n) ? "Yes":"No") << '\n';
#define CFYN(n) cout << ( (n) ? "YES":"NO") << '\n';
#define OUT(n) cout << (n) << '\n';
using ll = long long;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;

constexpr int MOD = 1000000007;

int mod(const ll &x){
    return x > 0 ? x % MOD : (x % MOD + MOD) % MOD;
}

int modm(const ll &x,const ll &m){
    return (x % MOD) * (m % MOD) % MOD;
}

int modpow(ll x, ll p) {
    int ret = 1;
    while(p > 0) {
        if (p & 1) ret = modm(ret,x);
        x = modm(x,x);
        p >>= 1;
    }
    return ret;
}

// x * modinv(d)
int modd(ll x,ll d) {
    return modm(x,modpow(d,MOD-2));
}
int main(void)
{
    IOS
    int n, p;
    cin >> n >> p;
    OUT(modm(p-1,modpow(p-2,n-1)))

    return 0;
}

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

using ll = long long;
static const ll MOD = 1e9 + 7;

// 繰り返し自乗法(x^nをmで割った余り) O(logn)
ll power(ll x, ll n, ll m) {
  ll res = 1;
  if (n > 0) {
    res = power(x, n / 2, m);
    if (n % 2 == 0) res = (res * res) % m;
    else res = ((res * res % m) * x) % m;
  }
  return res;
}

int main() {
  ll n, p;
  cin >> n >> p;

  if (n == 1) {
    cout << p - 1 << '\n';
    return 0;
  }

  cout << power(p - 2, n - 1, MOD) * (p - 1) % MOD << '\n';
}


//  “Alhamdulillah for Everything”
#include<bits/stdc++.h>
using namespace std;

#define      pai              acos(-1)
#define      ff               first
#define      ss               second
#define      ll               long long
#define      pb               push_back
#define      mp               make_pair
#define      pll              pair<ll,ll>
#define      sz(a)            (ll)a.size()
#define      endl             "\n"
#define      gcd(a, b)        __gcd(a, b)
#define      lcm(a, b)        ((a*b)/gcd(a,b))
#define      all(vec)         vec.begin(),vec.end()
#define      ms(a, b)         memset(a,b,sizeof(a))
#define      rep(i,n)         for(int i= 0; i < int(n); i++)
#define      rep1(i,n)        for(int i= 1; i <= n; i++)
#define      TEST_CASE(t)     for(int zz=1;zz<=t;zz++)
#define      PRINT_CASE       printf("Case %d: ",zz)
#define      fii              freopen("input.txt","r",stdin);
#define      foo              freopen("output.txt","w",stdout);
#define      boom             ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);

const ll M   = 1e9+7;
const ll mxn = 1e5+7;
const ll inf = 1e18;

int  main()
{
    ll i,j,k,a,b,c,d,n,m,t,x,y,z,u,v;
    cin>>n;
    ll ans=0;
    for(i=1;((i*(i+1))/2)<=n;i++)
    {
        a=n;
        a-=(i*(i+1))/2;
        if(a%i==0)
        {
            ans+=1;
        }
    }
    ans<<=1;
    cout<<ans<<endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pb push_back

LL n;
LL F[91];
vector<int> seq;
vector<int> ans;

int main()
{
	cin>>n;
	F[1]=F[2]=1;
	for(int i=3;i<=90;i++)
		F[i]=F[i-1]+F[i-2];
	for(int i=90;i>=1;i--)
		if(n>=F[i]) n-=F[i],seq.pb(1);
		else if(seq.size()) seq.pb(0);
	reverse(seq.begin(),seq.end());
	seq.pop_back();
	reverse(seq.begin(),seq.end());
	int P=seq.size()&1;
	ans.pb(1+P);
	for(int i=0;i<seq.size();i++)
	{
		P=1-P;
		ans.pb(3+P);
		if(seq[i]) ans.pb(1+P);
	}
	cout<<ans.size()<<'\n';
	for(int i=0;i<ans.size();i++)
		cout<<ans[i]<<'\n';

	return 0;
}


#include <bits/stdc++.h>
//#include <atcoder/modint>
//#include <atcoder/math>
//#include <boost/multiprecision/cpp_int.hpp>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("O3")
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPP(i, n) for(int i = 1; i <= n; i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define EPS (1e-9)
#define INF (1e17)
#define PI (acos(-1))
//const double PI = acos(-1);
//const double EPS = 1e-15;
//long long INF=(long long)1E17;
#define i_7 (long long)(1e9+7)
//#define i_7 998'244'353
long mod(long a){
    long long c = a % i_7;
    if(c >= 0) return c;
    return c + i_7;
}
long long po(long a, long b){
    if(b == 0) return 1;

    long long z = po(a , b / 2);
    z = mod(z * z);
    if(b % 2 != 0) z = mod(a * z);
    return z;
}

bool prime_(int n){
  if(n == 1){
    return false;
  }else if(n == 2){
    return true;
  }else{
    for(int i = 2; i <= std::sqrt(n); i++) if(n % i == 0) return false;
    return true;
  }
}

long long gcd_(long long a, long long b){
  if(a < b) std::swap(a,b);
  if(a % b == 0) return b;
  else return gcd_(b, a % b);
}

long long lcm_(long long x, long long y){
  return (x / gcd_(x,y)) * y;
}

using namespace std;
//using namespace atcoder;
//using mint = modint1000000007;
//using mint = modint998244353;
//using namespace boost::multiprecision;
//using namespace __gnu_pbds;

vector<int> a;
vector<vector<int>> G;
vector<int> dp;
const int limit = -(1e9 + 100);
int dfs(int v){
  if(dp[v] != limit) return dp[v];
  int res = limit;
  for(int nv: G[v]){
    res = max(res, a[nv]);
    res = max(res, dfs(nv));
  }
  return dp[v] = res;
}

int main(){
  //using namespace std;
  int n, m;
  cin>>n>>m;
  a.resize(n);
  REP(i, n) cin>>a[i];
  G.resize(n);
  int x[m], y[m];
  REP(i, m){
    cin>>x[i]>>y[i];
    x[i]--; y[i]--;
  }

  REP(i, m) G[x[i]].push_back(y[i]);
  dp.resize(n, limit);
  int ans = limit;
  for(int i = n - 1; i >= 0; i--){
    int temp = dfs(i) - a[i];
    ans = max(ans, temp);
  }
  cout << ans << endl;
  return 0;
}

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

const int N = 2e5+2;
int nums1[N];
int nums[N]; //进入i的最小值
bool vis[N];
int n,m,x,y;

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>nums1[i];
        nums[i] = 1e9;
    }
    vector<pair<int,int>> vp;
    for(int i=0;i<m;i++){
        cin>>x>>y;
        vp.emplace_back(make_pair(x,y));
    }
    sort(vp.begin(),vp.end());
    for(int i=0;i<m;i++){
        int st = vp[i].first;
        int end = vp[i].second;
        nums[end] = min(nums[end],min(nums[st],nums1[st]));
        vis[end] = 1;
        //cout<<st<<" "<<end<<" "<<nums[end]<<endl;
    }

    int res = -1e9;
    for(int i=1;i<=n;i++){
        //cout<<i<<" "<<nums1[i]-nums[i]<<" "<<vis[i]<<endl;
        if(vis[i])
        {
            res = max(res,nums1[i]-nums[i]);
        }
    }

    cout<<res<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i = (m); i <= (n); i++)
#define zep(i,m,n) for(ll i = (m); i < (n); i++)
#define rrep(i,m,n) for(ll i = (m); i >= (n); i--)
#define print(x) cout << (x) << endl;
#define printa(x,m,n) for(int i = (m); i <= n; i++){cout << (x[i]) << " ";} cout<<endl;

ll n, l, a[100008], b[100008];

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

    cin >> n >> l;
    rep(i, 1, n)cin >> a[i];
    rep(i, 1, n)cin >> b[i];
    a[0] = 0;
    b[0] = 0;
    a[n + 1] = l + 1;
    b[n + 1] = l + 1;
    n += 2;

    vector<ll> f;
    zep(i, 0, n)if(a[i] == b[i])f.push_back(i);

    ll m = f.size();

    ll ans = 0;
    zep(i, 0, m - 1){
        ll B = f[i];
        bool flag = false;
        rep(j, f[i] + 1, f[i + 1] - 1){
            if(b[j] < a[j]){
                if(flag){print(-1) return 0;}
                B = j;
            }else{
                flag = true;
            }
        }

        map<ll, ll> L;
        L[b[f[i]] - f[i]] = f[i];
        rep(j, f[i] + 1, B){
            if(L.find(b[j] - j) == L.end()){
                print(-1) return 0;
            }else{
                ans += j - L[b[j] - j];
                L[b[j] - j] = j;
            }

            L[a[j] - j] = j;
        }
        //print(ans)

        map<ll, ll> R;
        R[b[f[i + 1]] - f[i + 1]] = f[i + 1];
        rrep(j, f[i + 1] - 1, B + 1){
            if(R.find(b[j] - j) == R.end()){
                print(-1) return 0;
            }else{
                ans += R[b[j] - j] - j;
                R[b[j] - j] = j;
            }

            R[a[j] - j] = j;
        }
        //print(ans)
    }

    print(ans)

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef vector<ll> vl;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<char> vc;
typedef queue<ll> ql;
typedef deque<ll> dql;
typedef priority_queue<ll> pql;
typedef set<ll> sl;
typedef pair<ll, ll> pl;
typedef vector<vl> vvl;
typedef vector<pl> vpl;
#define rep(i, n) for(ll i = 0; i < ll(n); i++)
#define rep2(i, k, n) for(ll i = ll(k); i <= ll(n); i++)
#define rep3(i, n, k) for(ll i = ll(n); i >= ll(k); i--)
#define all(v) (v).begin(), (v).end()
ll mod(ll a, ll b) {if(b == 0) return 0; return (a % b + b) % b;}
bool chmin(ll &a, ll b) {if(b < a) {a = b; return 1;} return 0;}
bool chmax(ll &a, ll b) {if(b > a) {a = b; return 1;} return 0;}
const ll INF = 1LL << 60;
const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;
const ll MAX = 1e5;
const char newl = '\n';

ll n, l;
bool t=1;
vl a(MAX+2), b(MAX+2), d(MAX+2);

ll go_right(ll L, ll r) {
  ll cnt = 0;
  rep2(l, L, r-1) {
    if(a[l] == b[l]) continue;
    ll from=l, to=r;
    while(to-from>1) {
      ll m = (from + to)/2;
      if(b[l] <= a[m] - m + l) to = m;
      else from = m;
    }
    if(b[l] != a[to] - to + l) {t=0; return 0;}
    rep2(i, l, to-1) a[i] = a[to] - to + i;
    cnt += to - l;
  }
  return cnt;
}

ll go_left(ll l, ll R) {
  ll cnt = 0;
  rep3(r, R, l+1) {
    if(a[r] == b[r]) continue;
    ll from=l, to=r;
    while(to-from>1) {
      ll m = (from + to)/2;
      if(b[r] >= a[m] - m + r) from = m;
      else to = m;
    }
    if(b[r] != a[from] - from + r) {t=0; return 0;}
    rep3(i, r, from+1) a[i] = a[from] - from + i;
    cnt += r - from;
  }
  return cnt;
}

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

  cin >> n >> l;
  a[0] = 0;
  a[n+1] = l+1;
  b[0] = 0;
  b[n+1] = l+1;
  rep2(i, 1, n) cin >> a[i];
  rep2(i, 1, n) cin >> b[i];
  rep(i, n+2) d[i] = b[i] - a[i];

  rep2(i, 1, n-1) if(d[i] > 0 && d[i+1] < 0) {cout << -1 << newl; return 0;}

  ll ans=0;
  for(ll r=0; r<=n+1;) {
    if(d[r]==0) r++;

    ll l=r;
    if(d[r]>0) {
      while(d[r]>0) r++;
      ans += go_right(l, r);
    }
    if(d[r]<0) {
      while(d[r]<0) r++;
      ans += go_left(l-1, r-1);
    }

    if(!t) {
      cout << -1 << newl;
      return 0;
    }
  }
  cout << ans << newl;
  return 0;
}