#include <algorithm>
// #include <atcoder/all>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <tuple>
#include <unordered_map>
#include <vector>
/*
cd $dir && g++ -std=c++17 -Wall -Wextra -O2 -DATCODERDEBUG
-I/mnt/d/MyProjects/atcoder/lib/ac-library $fileName && echo 'compilation ok!'
&&  ./a.out
*/
using namespace std;
#define REP(i, n) for (ll i = 0; i < ll(n); i++)
#define FOR(i, a, b) for (ll i = a; i <= ll(b); i++)
#define ALL(x) x.begin(), x.end()
#define dame(a)        \
  {                    \
    cout << a << endl; \
    return 0;          \
  }
typedef long long ll;

class dstream : public ostream {};

template <typename T>
dstream &operator<<(dstream &os, T v) {
#ifdef ATCODERDEBUG
  cout << "\033[1;31m" << v << "\033[0m";
#endif
  return os;
}

ostream &endd(std::ostream &out) {
#ifdef ATCODERDEBUG
  out << std::endl;
#endif
  return out;
}
dstream dout;

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  os << "[ ";
  for (auto const &x : v) {
    os << x;
    if (&x != &v.back()) {
      os << " : ";
    }
  }
  os << " ]" << endl;
  return os;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<vector<T>> &v) {
  os << "[" << endl;
  for (auto const &x : v) {
    os << " ";
    os << x;
  }
  os << "]" << endl;
  return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &v) {
  os << "[ " << v.first << " " << v.second << " ]" << endl;
  return os;
}

template <typename T, typename U, typename Comp = less<>>
bool chmax(T &xmax, const U &x, Comp comp = {}) {
  if (comp(xmax, x)) {
    xmax = x;
    return true;
  }
  return false;
}

template <typename T, typename U, typename Comp = less<>>
bool chmin(T &xmin, const U &x, Comp comp = {}) {
  if (comp(x, xmin)) {
    xmin = x;
    return true;
  }
  return false;
}

ll op(ll a, ll b) { return min(a, b); }

ll e() { return 1e17; }

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

  ll N, x, c;
  cin >> N;
  vector<vector<ll>> c2xs(N, vector<ll>());
  REP(i, N) {
    cin >> x;
    cin >> c;
    c2xs[c - 1].emplace_back(x);
  }

  REP(i, N) { sort(c2xs[i].begin(), c2xs[i].end()); }

  ll left = 0;
  ll right = 0;
  ll left_v = 0;
  ll right_v = 0;

  REP(c, N) {
    ll siz = c2xs[c].size();
    if (siz == 0) continue;

    ll minX = c2xs[c][0];
    ll maxX = c2xs[c][siz - 1];

    ll n_right_v = min(left_v + abs(left - minX), right_v + abs(right - minX)) +
                   (maxX - minX);
    ll n_left_v = min(right_v + abs(right - maxX), left_v + abs(left - maxX)) +
                  (maxX - minX);

    right_v = n_right_v;
    left_v = n_left_v;
    right = maxX;
    left = minX;

    dout << left << " " << left_v << " " << right << " " << right_v << endd;
  }

  ll ans = 1e17;
  chmin(ans, left_v + abs(left));
  chmin(ans, right_v + abs(right));

  cout << ans << endl;
  // cout << std::fixed << std::setprecision(15) << sqrt(ans) << endl;
}

#pragma GCC optimize("Ofast")
#include <limits.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <unordered_set>
#include <map>
#include <cmath>
#include <iomanip>
#include <string>
#include <deque>
#include <assert.h>
#include <random>
#include <ctime>
#include <unordered_map>
#include <complex>
#include <chrono>

#define pnode node*

using namespace std;

typedef long long ll;
typedef long double ld;

const ll mod = (ll)1e9 + 7;

ll pw(ll a, ll p) {
    if (p == 0) {
        return 1;
    }
	ll r1 = pw(a, p / 2);
    if (p % 2 == 0) {
		return (r1 * r1) % mod;
    } else {
        return (pw(a, p - 1) * a) % mod;
    }
}

ll rev(ll x) {
    return pw(x, mod - 2);
}

ll f[(ll)2e7];

ll c(ll n, ll k) {
    if (k > n) {
		return 0;
    }
    ll ans = 1;
//	cerr << n << " " << k << "\n";
    for (ll i = n; i >= n - k + 1; --i) {
        ans *= i;
        ans %= mod;
    }
//    cerr << ans << "\n";
    ans = (ans * rev(f[k])) % mod;
    return ans;
}

void solve(){
	f[0] = 1;
    for (ll i = 1; i < 2e7; ++i) {
        f[i] = (f[i - 1] * i) % mod;
    }
    ll n, m;
    vector < ll > a;
    cin >> n >> m;
    a.resize(n);
    ll sm = 0;
    for (ll i = 0; i < n; ++i) {
		cin >> a[i];
		sm += a[i];
    }
    sm += n;
    m += n;
    cout << c(m, sm) << "\n";
}

signed main(){
    ll t = 1;
    ios_base::sync_with_stdio(0);
    srand(time(0));
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout << setprecision(20);
    #ifdef DEBUG
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #else
    #endif
    while(t--){
        solve();
    }
}


// abc183_f
#include <bits/stdc++.h>
#ifdef LOCAL
#include "../cxx-prettyprint/prettyprint.hpp"
#endif
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;

#define REP(i, n) for (int (i) = 0 ; (i) < (int)(n) ; ++(i))
#define REPN(i, m, n) for (int (i) = m ; (i) < (int)(n) ; ++(i))
#define REP_REV(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i))
#define REPN_REV(i, m, n) for (int (i) = (int)(n) - 1 ; (i) >= m ; --(i))
#define ALL(x) x.begin(), x.end()

#define INF (ll)(1e9)
#define MOD (1000000007)

#define print2D(h, w, arr) REP(i, h) { REP(j, w) cout << arr[i][j] << " "; cout << endl; }
#define print_line(vec, n) {for(int idx=0;idx<(n-1);idx++) cout << (vec)[idx] << " "; cout << (vec)[(n)-1] << endl;}
template<class T> void print(const T& x){cout << x << "\n";}
template<class T, class... A> void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); }
struct PreMain {PreMain(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(20);}} premain;

struct UnionFind {
    vector<int> par; // par[i]:iの親の番号　(例) par[3] = 2 : 3の親が2
    vector<int> rank;
    vector<int> size; // size[i]: iが親なら連結成分の数

    vector<map<int, int>> info;

    UnionFind(int N, vector<int>& C) : par(N), rank(N), size(N), info(N) { //最初は全てが根であるとして初期化
        for(int i = 0; i < N; i++) {
            par[i] = i; rank[i] = 0; size[i] = 1;
            info[i][C[i]]++;
        }

    }

    int find(int x) { // データxが属する木の根を再帰で得る：find(x) = {xの木の根}
        if (par[x] == x) return x;
        return par[x] = find(par[x]);
    }

    void unite(int x, int y) { // xとyの木を併合
        int rx = find(x); //xの根をrx
        int ry = find(y); //yの根をry
        if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま

        // rank[rx] >= rank[ry] となるように rx と ry を swap
        if(rank[rx] < rank[ry]) swap(rx, ry);

        // 同じ高さだったならばまとめたことによって高さ +1
        if(rank[rx] == rank[ry]) ++rank[rx];

        par[ry] = rx; // root rx に ry の木をつなぐ
        size[rx] += size[ry];
        size[ry] = 0;
        for (auto e: info[ry]){
            info[rx][e.first] += e.second;
        }

    }

    bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す
        int rx = find(x);
        int ry = find(y);
        return rx == ry;
    }

    int get_size(int x){
        int rx = find(x);
        return size[rx];
    }
};

int main() {
#ifdef LOCAL
    ifstream in("../arg.txt"); cin.rdbuf(in.rdbuf());
#endif

    int N, Q;
    cin >> N >> Q;

    vector<int> C(N);
    REP(i, N){
        cin >> C[i]; C[i]--;
    }

    UnionFind uf(N, C);

    REP(i, Q){
        int t;
        cin >> t;
        if (t == 1){
            int a, b;
            cin >> a >> b; a--; b--;
            if (not uf.same(a, b)){
                uf.unite(a, b);
            }

        } else {
            int x, y;
            cin >> x >> y; x--; y--;
            int ans = uf.info[uf.find(x)][y];
            print(ans);
        }

    }

    return 0;
}

#define _GLIBCXX_DEBUG
// #include <bits/stdc++.h>
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <unordered_set>
#include <utility>
#include <tuple>
using namespace std;

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

const ll INF = 1ll << 60; // 十分大きい値とする (ここでは 2^60)
const ll MOD = 1000000009;

template<class T> void chmin(T &a, T b) {
  if (a > b) a = b;
}

template<class T> void chmax(T &a, T b) {
  if (a < b) a = b;
}

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

  vector< tuple<ll, ll, ll> > p(N);
  rep(i, N) {
    ll A, B;
    cin >> A >> B;
    p[i] = make_tuple(2*A + B, A, B);
  }

  sort(p.begin(), p.end());
  reverse(p.begin(), p.end());
  /*
  cout << endl;
  rep(i, N) {
    cout << get<1>(p[i]) << " " << get<2>(p[i]) << endl;
  }
  cout << endl;
  */

  ll score_T = 0, score_A = 0;
  rep(i, N) score_A += get<1>(p[i]);

  // cout << score_A << " " << score_T << endl;
  rep(i, N) {
    ll A, B;
    A = get<1>(p[i]);
    B = get<2>(p[i]);
    score_A -= A;
    score_T += A + B;
    // cout << score_A << " " << score_T << endl;
    if (score_T > score_A) {
      cout << i+1 << endl;
      break;
    }
  }
}


#include<bits/stdc++.h>

using namespace std;
#define IOS { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }

typedef unsigned long long ull;
typedef long long int ll;
typedef long double ld;
#define REP(i,a,b) for(ll i=a;i<=b;++i)
#define REV(i,a,b) for(ll i=a;i>=b;i--)
#define pll pair<ll,ll>
#define vll vector<ll>
#define sll set<ll>
#define vpll vector<pll>
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define min_pq priority_queue <ll, vector<ll>, greater<ll> >
#define max_pq priority_queue <ll>
#define deci(n) fixed << setprecision(n)
#define INF 1e18

ll mod=1000000007;
////__RANGE__UPDATE___///
vector<ll> initializeDiffArray(vector<ll>& A);
void update(vector<ll>& D, ll l, ll r, ll x);
void getArray(vector<ll>& A, vector<ll>& D);
////__RANGE__UPDATE___///
ll min(ll a,ll b);
ll max(ll a,ll b);
ll gcd(ll a, ll b);
void swap(ll *a,ll *b);
ll lcm(ll a, ll b);
ll modpower(ll x, ll y, ll p);

//Only for integer y's
ll power(ll x, ll y);
ll modulo( ll value, ll m);
ll myXOR(ll x, ll y) ;
ll diff(ll a,ll b);

int main()
{
  IOS;
  /*  #ifdef DEBUG
    freopen("std.in", "r", stdin);
    freopen("std.out", "w", stdout);
    #else
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif */
    ll rep=1;

    //cin>>rep;
    while(rep--)
    {
    ll n,k,m;cin>>n>>k>>m;
    ll s=0;
    ll a[n];REP(i,0,n-2){ll t;cin>>t;s+=t;}

    if((s+k)/n<m)cout<<-1<<'\n';
    else

    {
        cout<<max(0,m*(n)-s)<<'\n';
    }

    }
    return 0;

}

ll myXOR(ll x, ll y)
{
   return (x | y) & (~x | ~y);
}

ll min(ll a,ll b)
{
  if(a>b)
  return b;
  return a;
}

ll max(ll a,ll b)
{
  if(a<b)
  return b;
  return a;
}

ll gcd(ll a, ll b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}

ll diff(ll a,ll b)
{
  if(a>b)
  return a-b;
  return b-a;
}

void swap(ll *a,ll *b)
{
  ll t=*a;
  *a=*b;
  *b=t;
}

ll lcm(ll a, ll b)
{
    if(a==0)
    return b;
    if(b==0)
    return a;
    return (a*b)/gcd(a, b);
}

ll modpower(ll x, ll y, ll p)
{
    ll res = 1;      // Initialize result

    x = x % p;  // Update x if it is more than or
                // equal to p

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res*x) % p;

        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

ll power(ll x, ll y)
{
    ll temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}

ll modulo( ll value, ll m)
{
    ll mod = value % m;
    if (value < 0) {
        mod += m;
    }
    return mod;
}

vector<ll> initializeDiffArray(vector<ll>& A)
{
    ll n = A.size();

    // We use one extra space because
    // update(l, r, x) updates D[r+1]
    vector<ll> D(n + 1);

    D[0] = A[0], D[n] = 0;
    for (ll i = 1; i < n; i++)
        D[i] = A[i] - A[i - 1];
    return D;
}

// Does range update
void update(vector<ll>& D, ll l, ll r, ll x)
{
    D[l] += x;
    D[r + 1] -= x;
}

// Prints updated Array
void getArray(vector<ll>& A, vector<ll>& D)
{
    for (ll i = 0; i < A.size(); i++) {
        if (i == 0)
            A[i] = D[i];

        // Note that A[0] or D[0] decides
        // values of rest of the elements.
        else
            A[i] = D[i] + A[i - 1];
    }
}

#include <bits/stdc++.h>
using namespace std;
//actual solution is at bottom//
////<pbds>////
/*
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>,
    rb_tree_tag, tree_order_statistics_node_update>;
// change null_type for map
// change less to less_equal for multiset
#define ook order_of_key
#define fbo find_by_order*/
///</pbds>///

#define int long long int
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define sz(x) (int)x.size()
#define google(i) cout<<"Case #"<<i<<" :";
///<constants>///
const int MOD = 1e9+7; // 998244353; // = (119<<23)+1
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = 4*atan((ld)1);
const int xd[4] = {0,1,0,-1}, yd[4] = {1,0,-1,0};
///</constants>///

///<IO>///
namespace io {
    void setIn(string s) { freopen(s.c_str(),"r",stdin); }
    void setOut(string s) { freopen(s.c_str(),"w",stdout); }
    void setIO(string s = "") {
        ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
        // cin.exceptions(cin.failbit); // ex. throws exception when you try to read letter into int
        if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
    }
}

using namespace io;
///</IO>///

///<execution-time>///
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
/*example for clock usage
    clock_t z = clock();
    debug("Total Time: %.3f\n", (double)(clock() - z) / CLOCKS_PER_SEC);
*/
///</execution-time>///
signed main(){
    setIO("");
	int a,b,c,d;cin>>a>>b>>c>>d;
	cout<<(a*d-b*c);
    return 0;
}
/* stuff you should look for
    * check whether you have read the problem correctly
    * int overflow, array bounds
    * special cases (n=1?), slow multiset operations
    * do smth instead of nothing and stay organized
*/


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

vector<bool> consumed;
vector<set<int>> v;

void dfs(int i) {

    consumed[i] = true;
    for(auto e : v[i]) {
        if(!consumed[e])
            dfs(e);
    }
}

#ifndef _LOCAL
int main() {
    int n, m;
    cin >> n >> m;
    vector<ll> a(m), b(m);
    for(int i = 0; i < m; i++)
        cin >> a[i] >> b[i];

    for(int i = 0; i < m; i++) {
        a[i]--;
        b[i]--;
    }
    v = vector<set<int>>(n, set<int>());
    for(int i = 0; i < m; i++) {
        v[a[i]].insert(b[i]);
    }
    ll ans = 0ll;
    for(int i = 0; i < n; i++) {
        consumed = vector<bool>(n, false);
        dfs(i);
        for(int j = 0; j < n; j++)
            if(consumed[j])
                ans++;
        /*
        cout << i << " -> ";
        for(int j = 0; j < n; j++)
            if(consumed[j])
                cout << j << " ";
        cout << endl;
        */
    }
    cout << ans << endl;
    return 0;
}
#endif

/* これを翻訳している間、あなたはあなたの人生のいくつかの貴重な瞬間を無駄にしました */

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

#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define pb push_back
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
#define S(x) (int)(x).size()
#define L(x) (int)(x).length()
#define ld long double
#define mem(x,y) memset(x,y,sizeof x)

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int , null_type , less<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_set;

const int mod = 1e9+7;
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
const int infi = 0x3f3f3f3f;

bool vis[30];
vector<int> ord;
int adj[30][30];
int choice[30];

void dfs(int v)
{
	vis[v]=1;
	ord.pb(v);

	for(int i=1;i<=20;i++)
	{
		if(adj[v][i]==1 && !vis[i]) dfs(i);
	}
}

ll f(int ind, int c)
{
	if(ind == S(ord)-1) return 1;
	choice[ord[ind]]=c;
	set<int> nxt={1,2,3};
	for(int i=0;i<=ind;i++)
	if(adj[ord[i]][ord[ind+1]]==1) nxt.erase(choice[ord[i]]);
	ll ret=0;
	for(auto u:nxt) ret += f(ind+1,u);
	return ret;
}

int main()
{
	IOS
	int n,m;
	cin>>n>>m;
	for(int i=0;i<m;i++)
	{
		int a,b;
		cin>>a>>b;
		adj[a][b]=adj[b][a]=1;
	}
	ll ans=1;

	for(int i=1;i<=n;i++)
	{
		if(!vis[i])
		{
			dfs(i);
			ans *= (f(0,1)+f(0,2)+f(0,3));
			ord.clear();
		}
	}
	cout<<ans<<'\n';
}


#include<iostream>
#include<iomanip>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<cstring>
#include<tuple>
#define rep(i,n) for(int i = 0;i < (n);i++)
using namespace std;
using ll = long long;
const int mod = 1e9 + 7;
// {g,x y} : ax * by = g
tuple<ll,ll,ll> extgcd(ll a,ll b){
    if(b == 0) return {a,1,0};
    ll g,x,y;
    tie(g,x,y) = extgcd(b, a % b);
    return {g,y,x - a / b * y};
}
void solve(){
    int n,s,k;
    cin >> n >> s >> k;
    ll g,x,y;
    tie(g,x,y) = extgcd(k,n);
    if(s % g != 0){
        cout << -1 <<endl;
        return;
    }
    n /= g;
    s /= g;
    k /= g;
    ll ans = ((x* - s) % n + n) % n;
    cout << ans << endl;
}
int main(){
    int t;
    cin >> t;
    rep(i,t){
        solve();
    }
    return 0;

}

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

int dp[101][505001];

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int n,k,mod; cin >> n >> k >> mod;
	dp[0][0]=1;
	int sum=0;
	for(int i=1;i<=n;i++){
		sum+=i;
		vector<int> ps(i);
		for(int j=0;j<=sum*k;j++){
			int x=j%i;
			(ps[x]+=dp[i-1][j])%=mod;
			if(j-i*(k+1)>=0) (ps[x]-=dp[i-1][j-i*(k+1)])%=mod;
			dp[i][j]=ps[x];
			if(dp[i][j]<0)dp[i][j]+=mod;
		}
	}
	sum=0;
	for(int i=1;i<=n;i++){
		sum+=i;
		ll res=0;
		for(int j=0;j<=sum*k;j++){
			(res+=(ll)dp[i-1][j]*(ll)dp[n-i][j]%mod)%=mod;
		}
		res=res*(k+1)-1;
		res%=mod;
		if(res<0)res+=mod;
		cout << res << "\n";
	}
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define pll pair<ll,ll>
#define pii pair<int,int>
#define rep(i,n) for(ll i=0;i<n;i++)
#define For(i,a,b) for(int i=a;i<b;i++)
#define sz(x) ((ll)(x).size())
#define pb push_back
#define mp make_pair
#define bit(n) (1LL<<(n))
#define F first
#define S second
#define debug(x) cerr << x << endl
#define Complex complex<double>
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
const ll INF = 1LL<<60;
const ll mod = (int)1e9 + 7;

class UnionFind {
public:
    vector <ll> par; // 各元の親を表す配列
    vector <ll> siz; // 素集合のサイズを表す配列(1 で初期化)

    // Constructor
    UnionFind(ll sz_): par(sz_), siz(sz_, 1LL) {
        for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
    }
    void init(ll sz_) {
        siz.assign(sz_, 1LL);  // assign: 再代入
        par.resize(sz_);  // resize: 再確保
        for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
    }

    // Member Function
    // Find
    ll root(ll x) { // 根の検索
        while (par[x] != x) {
            x = par[x] = par[par[x]]; // x の親の親を x の親とする
        }
        return x;
    }

    // Union(Unite, Merge)
    bool merge(ll x, ll y) {
        x = root(x);
        y = root(y);
        if (x == y) return false;
        // merge technique（データ構造をマージするテク．小を大にくっつける）
        if (siz[x] < siz[y]) swap(x, y);
        siz[x] += siz[y];
        par[y] = x;
        return true;
    }

    bool issame(ll x, ll y) { // 連結判定
        return root(x) == root(y);
    }

    ll size(ll x) { // 素集合のサイズ
        return siz[root(x)];
    }
};

int main() {
    int n,m;
    cin >> n >> m;
    ll a[n];
    rep(i,n)cin >> a[i];
    ll b[n];
    rep(i,n)cin >> b[i];
    UnionFind tree(n);
    rep(i,m){
        int c,d;
        cin >> c >> d;
        c--;
        d--;
        tree.merge(c,d);
    }
    rep(i,n){
        if(tree.root(i)!=i){
            a[tree.root(i)]+=a[i];
            b[tree.root(i)]+=b[i];
        }
    }
    rep(i,n){
        if(tree.root(i)==i){
            if(a[i]!=b[i]){
                cout << "No";
                return 0;
            }
        }
    }
    cout << "Yes";
    return 0;
}

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

struct UnionFind {
    //自身が親であれば、その集合に属する頂点数に-1を掛けたもの
    //そうでなければ親のid
    vector<int> r;

    UnionFind(int N) {
        r = vector<int>(N, -1);
    }

    int root(int x) {
        if (r[x] < 0) return x;
        return r[x] = root(r[x]);
    }

    bool unite(int x, int y) {
        x = root(x);
        y = root(y);
        if (x == y) return false;
        if (r[x] > r[y]) swap(x, y);
        r[x] += r[y];
        r[y] = x;
        return true;
    }

    int size(int x) {
        return -r[root(x)];
    }
};

int main(){
    int n, m; cin >> n >> m;
    vector<int> a(n), b(n);
    for(int i=0; i<n; ++i){cin >> a[i];}
    for(int i=0; i<n; ++i){cin >> b[i];}
    UnionFind uf(n);
    vector<vector<int>> g(n);
    for(int i=0; i<m; ++i){
        int c, d; cin >> c >> d; c--; d--;
        g[c].push_back(d); g[d].push_back(c);
        uf.unite(c, d);
    }
    vector<ll> sa(n, 0), sb(n, 0);
    for(int v=0; v<n; ++v){
        int r = uf.root(v);
        sa[r] += a[v]; sb[r] += b[v];
    }
    bool res = true;
    for(int v=0; v<n; ++v){
        int r = uf.root(v);
        if(sa[r]!=sb[r]){res = false;}
    }
    if(res) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a[1111],b[1111];
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		int ans = 111111111;
		for(int i =1 ; i <= n ; i++){
			scanf("%d %d",&a[i],&b[i]);
		}
		for(int i = 1; i <= n ; i++){
			for(int j = 1 ; j <= n ; j++)
				if(i == j){
					ans = min (ans, a[i]+b[j]);
				}else ans = min (ans, max(a[i],b[j]));
		}
		printf("%d\n",ans);
	}
	return 0;
}

#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)

int main()
{
  int n;
  cin >> n;
  int a[n], b[n];
  rep(i, n)
  {
    cin >> a[i] >> b[i];
  }
  int time[2] = {a[0], b[0]};
  int ans;
  rep(i, n)
  {
    rep(j, n)
    {
      if (i == j)
      {
        if (a[i] + b[i] <= max(time[0], time[1]))
        {
          time[0] = a[i];
          time[1] = b[j];
          ans = time[0] + time[1];
        }
      }
      else
      {
        if (max(a[i], b[j]) <= max(time[0], time[1]))
        {
          time[0] = a[i];
          time[1] = b[j];
          ans = max(time[0], time[1]);
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
template <class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937/*_64*/ rng(chrono::steady_clock::now().time_since_epoch().count());
#define printArr(arr, n) cerr << #arr << " = ["; for(int i=0; i<(n); i++){if (i) cerr << ", "; cerr << arr[i];} cerr << "]\n"
template<class A> ostream& operator<<(ostream &cout, vector<A> const &v) {cout << "["; for(int i = 0; i < v.size(); i++) {if (i) cout << ", "; cout << v[i];} return cout << "]";};
template<class A, class B> ostream& operator<<(ostream &cout, const pair<A,B> &x) {return cout << "(" <<x.first << ", " << x.second << ")";};
void _print() {cerr << "]\n";}
template <class T, class... V> void _print(T t, V... v) {cerr << t; if (sizeof...(v)) cerr << ", "; _print(v...);}
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#define fi first
#define se second
#define SZ(x) (int)((x).size())
#define pii pair<int,int>
template<int modd> struct modint {
	static const int mod = modd;
	int v; explicit operator int() const { return v;}
	modint() : v(0) {}
	modint(ll x) : v(int(x%mod)) {if (v < 0) v += mod;}
	friend bool operator==(const modint& a, const modint& b) {return a.v == b.v;}
	friend bool operator!=(const modint& a, const modint& b) {return a.v != b.v;}
	friend bool operator<(const modint& a, const modint& b) {return a.v < b.v;}
	modint& operator+=(const modint& a) {if ((v += a.v) >= mod) v -= mod; return *this;}
	modint& operator-=(const modint& a) {if ((v -= a.v) < 0) v += mod; return *this;}
	modint& operator*=(const modint& a) {v = int((ll)v*a.v%mod); return *this;}
	modint& operator/=(const modint& a) {return (*this) *= inv(a);}
	friend modint pow(modint a, ll p) {modint ret = 1; for (; p; p /= 2, a *= a){if (p&1) ret *= a;} return ret;}
	friend modint inv(const modint& a) {return pow(a,mod-2);}
	modint operator-() const {return modint(-v);}
	modint& operator++() {return *this += 1;}
	modint& operator--() {return *this -= 1;}
	friend modint operator+(modint a, const modint& b) {return a += b;}
	friend modint operator-(modint a, const modint& b) {return a -= b;}
	friend modint operator*(modint a, const modint& b) {return a *= b;}
	friend modint operator/(modint a, const modint& b) {return a /= b;}
	friend ostream& operator<<(ostream& out, modint a) {return out << a.v;}
	friend istream& operator>>(istream& in, modint& a) {ll b; in >> b; a.v = b; return in;}
};
using mint = modint<1000000007>;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n; char aa,ab,ba,bb;
	cin >> n >> aa >> ab >> ba >> bb;
	if (n == 2) {
		cout << "1\n";
		return 0;
	}
	if (ab == 'B') {
		if (bb == 'B') {
			cout << "1\n";
			return 0;
		} else {
			if (ba == 'A') {
				mint ans = pow(mint(2),n-3);
				cout << ans << "\n";
				return 0;
			} else {
				vector<vector<mint>> dp(n,vector<mint>(2));
				dp[1][1] = 1;
				for (int q = 2; q < n-1; q++) {
					dp[q][1] = dp[q-1][0]+dp[q-1][1];
					dp[q][0] = dp[q-1][1];
				}
				cout << dp[n-2][0]+dp[n-2][1] << "\n";
				return 0;
			}
		}
	}
	if (ab == 'A') {
		if (aa == 'A') {
			cout << "1\n";
			return 0;
		} else {
			if (ba == 'B') {
				mint ans = pow(mint(2),n-3);
				cout << ans << "\n";
				return 0;
			} else {
				vector<vector<mint>> dp(n,vector<mint>(2));
				dp[1][1] = 1;
				for (int q = 2; q < n-1; q++) {
					dp[q][1] = dp[q-1][0]+dp[q-1][1];
					dp[q][0] = dp[q-1][1];
				}
				cout << dp[n-2][0]+dp[n-2][1] << "\n";
				return 0;
			}
		}
	}

	return 0;
}

#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstdint>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
#define MP make_pair
#define PB push_back
#define inf 1000000007
#define rep(i,n) for(int i = 0; i < (int)(n); ++i)
#define all(x) (x).begin(),(x).end()

template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){
    std::fill( (T*)array, (T*)(array+N), val );
}

template<class T> inline bool chmax(T &a, T b){
    if(a<b){
        a = b;
        return true;
    }
    return false;
}

template<class T> inline bool chmin(T &a, T b){
    if(a>b){
        a = b;
        return true;
    }
    return false;
}

int main(){
    int n,L;
    cin >> n >> L;
    vector<int> a(n+1);
    a[0] = 0;
    rep(i,n) cin >> a[i+1];
    a.push_back(L+1);
    vector<int> b(n+1);
    b[0] = 0;
    rep(i,n) cin >> b[i+1];
    b.push_back(L+1);
    n+=2;
    vector<int> p;
    rep(i,n){
        if(a[i]>b[i]){
            p.push_back(-1);
        }else if(a[i]==b[i]){
            p.push_back(0);
        }else{
            p.push_back(1);
        }
    }
    ll res = 0;
    int id = 0;
    int left = 0;
    int dir = 0;
    while(id!=n+1){
        if(dir!=p[id]){
            if(dir==1){
                if(p[id]==-1){
                    cout << -1 << endl;
                    return 0;
                }
                while(p[left]==0)left++;
                int right = id;
                // cerr <<"test2 " <<  left << " " << right << endl;
                ll c = 1;
                int L = b[left];
                for(int i = left+1;i<=right;i++){
                    int now = a[i];
                    if(now - c == L){
                        res += c;
                        left++;
                        c--;
                        while(left<=right&&now-c==b[left]){
                            c--;
                            left++;
                        }
                        L = b[left];
                    }
                    c++;
                }
                if(c!=0){
                    cout << -1 << endl;
                    return 0;
                }
            }
            if(dir==-1){
                int right = id-1;
                // cerr <<"test:" <<  left << " " << right << endl;
                ll c = 1;
                int R = b[right];
                for(int i = right-1;i>=left;i--){
                    int now = a[i];
                    // cerr << now << " " << c << " " << R << endl;
                    if(now + c == R){
                        res += c;
                        right--;
                        c--;
                        while(right>i&&now+c==b[right]){
                            c--;
                            right--;
                        }
                        R = b[right];
                    }
                    c++;
                }
                // cerr << c << endl;
                if(c!=1){
                    cout << -1 << endl;
                    return 0;
                }
                left = id;
            }
            dir = p[id];
        }
        if(dir==0&&p[id]==0){
            left = id;
        }
        // cerr << id << " " << res << endl;
        id++;
    }
    cout << res << endl;

    return 0;
}


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

#define fr(i,n) for(int i = 0; i<n; i++)
#define sz(v) (int)(v.size())
#define prin(a) cout << #a << " = " << a << endl
#define prinv(v) cout << #v << " = "; for(auto it : v) cout << it << ", "; cout << endl
#define all(v) (v).begin(),(v).end()

typedef long long ll;

#define rmin(a,b) a = min<ll>(a,b)
#define rmax(a,b) a = max<ll>(a,b)

#define fi first
#define se second

const int N = 19;
vector<pair<int,int>> ct[N];
ll dp[N][(1<<N)+10];
ll n, m;

bool ok(int mask, int i){
	for(auto &[tam,ns] : ct[i]){
		if(bitset<32>( ((1<<tam)-1)&(mask)).count()<ns) return 0;
	}
	return 1;
}

ll rec(int id, int mask){
	if(id==n) return 1;
	ll &ans = dp[id][mask];
	if(~ans) return ans;
	ans = 0;
	fr(i,n){
		if((mask&(1<<i))==0){
			int nmask = mask|(1<<i);
			if(ok(nmask,id)) ans+=rec(id+1,nmask);
		}
	}
	return ans;
}

int main(){
	ios::sync_with_stdio(0); cin.tie(0);
	 cin >> n >> m;
	fr(mm,m){
		ll xi, yi, zi; cin >> xi >> yi >> zi;
		yi = (n+1)-yi;
		yi--;
		yi--;

		ll need_smaller = max(0ll,xi-zi);
		if(need_smaller) ct[yi].emplace_back(xi,need_smaller);
	}

	memset(dp,-1,sizeof(dp));
	cout << rec(0,0) << "\n";
}


/**
 *    author:  FromDihPout
 *    created: 2021-06-22
**/

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

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

    int n;
    string s, x;
    cin >> n >> s >> x;

    reverse(s.begin(), s.end());
    reverse(x.begin(), x.end());
    vector<int> a(n);
    for (int i = 0, p = 1; i < n; i++, p = (p * 10) % 7) {
        a[i] = ((s[i] - '0') * p) % 7;
    }

    vector<bool> prev(7);
    if (x[0] == 'A' && a[0] == 0) {
        prev[0] = true;
    } else if (x[0] == 'T') {
        prev[0] = prev[7 - a[0]] = true;
    }
    for (int i = 1; i < n - 1; i++) {
        vector<bool> curr(7);
        for (int j = 0; j < 7; j++) {
            if (x[i] == 'A') {
                curr[j] = prev[(j + a[i]) % 7] && prev[j];
            } else {
                curr[j] = prev[(j + a[i]) % 7] || prev[j];
            }
        }
        prev = curr;
    }

    if (x[n - 1] == 'A') {
        cout << (prev[a[n - 1]] && prev[0] ? "Takahashi" : "Aoki") << '\n';
    } else {
        cout << (prev[a[n - 1]] || prev[0] ? "Takahashi" : "Aoki") << '\n';
    }
    return 0;
}

// 問題の URL を書いておく
//

#include <bits/stdc++.h>

using namespace std;

//#define ENABLE_PRINT

#if defined(ENABLE_PRINT)

#define Print(v) \
do {\
    cout << #v << ": " << v << endl; \
}while(0)

#define PrintVec(v) \
do {\
    for(int __i = 0; __i < v.size(); ++__i) \
    { \
        cout << #v << "[" << __i << "]: " << v[__i] << endl; \
    }\
}while(0)

#else

#define Print(v) ((void)0)
#define PrintVec(v) ((void)0)

#endif

#define rep(i, n) for(int i = 0; i < (int)(n); ++i)

using ll = long long;

// 0 なら高橋勝ち
// 1 なら青木勝ち
int calc(int round, int m, string& S, string& T, vector<vector<int>>& state)
{
    Print(round);
    Print(m);
    if(state[round][m] != -1) return state[round][m];

    // 最終ラウンド
    auto n = S[round] - '0';
    if(round == (int)state.size() - 1)
    {
        if(T[round] == 'A')
        {
            if(m != 0 || (m + n) % 7  != 0)
            {
                state[round][m] = 1;
            }
            else state[round][m] = 0;
        }
        else
        {
            if(m == 0 || (m + n) % 7  == 0)
            {
                state[round][m] = 0;
            }
            else state[round][m] = 1;
        }

        Print(state[round][m]);
        return state[round][m];
    }

    if(T[round] == 'A')
    {
        if(calc(round + 1, (m * 10) % 7, S, T, state) == 1 || calc(round + 1, (m + n) * 10 % 7, S, T, state) == 1)
        {
            state[round][m] = 1;
            return 1;
        }
        state[round][m] = 0;
        return 0;
    }
    else
    {
        if(calc(round + 1, (m * 10) % 7, S, T, state) == 0 || calc(round + 1, (m + n) * 10 % 7, S, T, state) == 0)
        {
            state[round][m] = 0;
            return 0;
        }
        state[round][m] = 1;
        return 1;
    }
}

int main(int, const char**)
{
    int N;
    cin >> N;
    string S, T;
    cin >> S >> T;

    vector<vector<int>> state(N, vector<int>(7, -1));

    auto ans = calc(0, 0, S, T, state);
    Print(ans);
    cout << (ans == 0 ? "Takahashi" : "Aoki") << endl;
    return 0;
}


//#include <tourist>
#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;
typedef long long ll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;

typedef pair<ll, ll> p;
const int INF = 1e9;
const double eps = 1e-7;
const ll LINF = ll(1e18);
const int MOD = 1000000007;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
const int Dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}, Dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
const long double pi = 4 * atan(1);
#define yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define no cout << "No" << endl
#define NO cout << "NO" << endl
#define rep(i, n) for (int i = 0; i < n; i++)
#define ALL(v) v.begin(), v.end()
#define debug(v)          \
    cout << #v << ":";    \
    for (auto x : v)      \
    {                     \
        cout << x << ' '; \
    }                     \
    cout << endl;
template <class T>
bool chmax(T &a, const T &b)
{
    if (a < b)
    {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
bool chmin(T &a, const T &b)
{
    if (b < a)
    {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v)
{
    for (T &x : v)
        is >> x;
    return is;
}
//cout<<fixed<<setprecision(15);有効数字15桁
//-std=c++14
//g++ yarudake.cpp -std=c++17 -I .
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    cin >> a;
    map<int, int> m;
    rep(i, n)
    {
        m[a[i]]++;
    }
    int ans = 0;
    int i = 1;
    int box = min(m[0],k);
    while(box){
        int h =  max(box - m[i],0);
        ans += h*i;
        chmin(box,m[i]);
        i++;
    }
    cout<<ans<<"\n";
}

#include <bits/stdc++.h>
using namespace std;
#define fastIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define all(c) (c).begin(), (c).end()

// !!READ THE PROBLEM STATEMENT CORRECTLY YOU STUPID, WORTHLESS PIECE OF SHIT!!
//Analyze testcases thoroughly before starting implementation
//Don't forget to read the stuff at the bottom

void solve() {
	int N, M;
	cin >> N >> M;
	vector <int> A(N), B(M);
	for (auto &a : A) cin >> a;
	for (auto &b : B) cin >> b;
	// this is equivalent to an edit distance problem
	vector <vector <int> > dp(N + 1, vector <int> (M + 1));
	for (int i = 1; i <= N; i++) {
		dp[i][0] = i;
		for (int j = 1; j <= M; j++) {
			dp[0][j] = j;
			dp[i][j] = min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (A[i - 1] != B[j - 1])});
		}
	}
	cout << dp[N][M];
}

int main() {
	fastIO;
	solve();
	cout << '\n';
	return 0;
}

/*
check for edge cases : n = 0, 1 etc
check for overflows and out of bounds
*/


#include <bits/stdc++.h>
using ll = long long;
using namespace std;
#define rep(i, n) for (int i = 0, i##_len = (int)(n); i < i##_len; i++)
#define reps(i, n) for (int i = 1, i##_len = (int)(n); i <= i##_len; i++)
#define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; i--)
#define rreps(i, n) for (int i = ((int)(n)); i > 0; i--)
#define repi(i, x) \
	for (auto i = (x).begin(), i##_fin = (x).end(); i != i##_fin; i++)
#define all(x) (x).begin(), (x).end()
#define F first
#define S second
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
typedef vector<int> Vi;
typedef vector<Vi> VVi;
typedef pair<int, int> Pi;
typedef vector<Pi> VPi;
typedef vector<long long> V;
typedef vector<V> VV;
typedef pair<long long, long long> P;
typedef vector<P> VP;
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;
}
template <class T, class U>
ostream& operator<<(ostream& os, const pair<T, U>& p) {
	os << "(" << p.first << " " << p.second << ")";
	return os;
}
template <class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
	rep(i, v.size()) {
		if (i) os << " ";
		os << v[i];
	}
	return os;
}
template <class T, class U>
istream& operator>>(istream& is, pair<T, U>& p) {
	is >> p.first >> p.second;
	return is;
}
template <class T>
istream& operator>>(istream& is, vector<T>& v) {
	rep(i, v.size()) { is >> v[i]; }
	return is;
}
const long long INFLL = 1LL << 60;
const int INF         = 1 << 30;
const double PI       = acos(-1);
#ifdef LOCAL
#define dbg(x) cerr << #x << ": " << (x) << '\n'
#define say(x) cerr << (x) << '\n'
#else
#define dbg(x)
#define say(x)
#endif
string solve(bool a) { return ((a) ? "Yes" : "No"); }
int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int n, m;
	// int up   = 1e9;
	// int down = 1;
	// bool can = false;
	cin >> n >> m;
	int margin = m + 1;
	dbg(margin);
	VPi ans(n);
	if (m == 0) {
		rep(i, n) { ans[i] = mp(i * 2 + 1, i * 2 + 2); }
	} else if (m < 0 || m > n - 2) {
		cout << -1 << endl;
		return 0;
	} else {
		for (int i = 1; i <= margin; i++) {
			ans[i - 1] = mp(2 * i, 2 * i + 1);
			dbg(ans[i - 1]);
		}
		ans[margin] = mp(1, 2 * margin + 2);
		dbg(ans[margin]);
		for (int i = margin + 1; i < n; i++) {
			ans[i] = mp(2 * margin + 2 + 2 * i, 2 * margin + 3 + 2 * i);
		}
	}
	rep(i, n) { cout << ans[i].F << " " << ans[i].S << endl; }
}
/*
1  9, 2 3 , 4 5 ,6 7 (2:2)

1 5, 6 9, 2 3 , 7 8 (0:0/0)

1 2 ,3 9, 4 5 ,6 7 (1 : 0/1)

2 3, 4 5, 6 7, (2n: 2n+1;n=1...M) +(1:2(M+1))
*/

//vs solve(int n){
//    vs ans;
//    per(bit,n){
//        rep(cases,1<<(n-1-bit)){
//            ll mask = 1<<bit;
//            rep(i,n-1-bit)
//                if(cases&(1<<i))
//                    mask ^= 1<<(bit+i+1);
//            string cur;
//            rep(i,1<<n)
//                if(__builtin_popcountll(i&mask)%2 == 1)
//                    cur += "A";
//                else
//                    cur += "B";
//
//            ans.pb(cur);
//        }
//    }
//    return ans;
//}
//void __(){
//    _(ll,k);
//    vector<string> ans;
//    rep(i,k){
//        string cur;
//        rep(j,(1<<k))
//            if(j&(1<<i))
//                cur += "A";
//            else
//                cur += "B";
//        ans.pb(cur);
//    }
//    ans = solve(k);
//    print sz(ans);
//    print_vn ans;
//                //if(_[i] != _[j])
//}
//
#include <iomanip>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#define pb push_back
#define REP_ZERO_INT(i,r) for(int i = 0; i < (r); ++i)
#define GET_REP_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define rep(...) GET_REP_MACRO(__VA_ARGS__,REP_ANY,REP_INT,REP_ZERO_INT)(__VA_ARGS__)
#define PER_ZERO_INT(i,r) for(int i = (r)-1; i >= 0; --i)
#define GET_PER_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define per(...) GET_PER_MACRO(__VA_ARGS__,PER_ANY,PER_INT,PER_ZERO_INT)(__VA_ARGS__)
#define all(v) (v).begin(), (v).end()
#define sz(v) ll(v.size())
#define T1 template<typename T> static
using namespace std;
typedef long long ll;
typedef vector<string> vs;
T1 ostream& operator<<(ostream& stream, const vector<T>& t);
T1 istream& read(T, T, istream& = cin);
struct _print {
    string sep,end;
    bool space;
    ostream &stream;
    _print(string _sep=" ",string _end="\n",
            ostream &_stream = cout)
        : sep(_sep),end(_end),space(false),
            stream(_stream) {}
    ~_print() { stream << end; }

    template <typename T>
        _print &operator , (const T &t) {
            if (space) stream << sep;
            space = true;
            stream << t;
            return *this;
        }
};
struct _print2{
    string s1,s2,end;
    bool space;
    ostream &stream;
    _print2(string _s1 = " ", string _s2 = " ", string _end="\n", ostream &_stream = cout)
        :s1(_s1),s2(_s2),end(_end),space(false),
        stream(_stream) {}
    ~_print2() { stream << end; }

    template <typename T>
        _print2 &operator , (const T &t) {
            for(auto _ : t){
                if (space) stream << s1;
                space = true;
                _print p(s2,"",stream);
                    p,_;
            }
            return *this;
        }
};
#define print _print(),
#define print_vn _print2("\n"," ","\n"),
#define INPUT_WITHOUT_INIT(type,name) type name; cin >> name
#define GET_INPUT_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define _(...) GET_INPUT_MACRO(__VA_ARGS__,_IWI,_IWI,_IWI,_IWI,_IWI,_IWI,INPUT_WITHOUT_INIT)(__VA_ARGS__)
vs solve(int n){
    vs ans;
    per(bit,n){
        rep(cases,1<<(n-1-bit)){
            ll mask = 1<<bit;
            rep(i,n-1-bit)
                if(cases&(1<<i))
                    mask ^= 1<<(bit+i+1);
            string cur;
            rep(i,1<<n)
                if(__builtin_popcountll(i&mask)%2 == 1)
                    cur += "A";
                else
                    cur += "B";

            ans.pb(cur);
        }
    }
    return ans;
}
void __(){
    _(ll,k);
    vector<string> ans;
    rep(i,k){
        string cur;
        rep(j,(1<<k))
            if(j&(1<<i))
                cur += "A";
            else
                cur += "B";
        ans.pb(cur);
    }
    ans = solve(k);
    print sz(ans);
    print_vn ans;
                //if(_[i] != _[j])
}

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


#pragma region header
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n)for(int i=0;i<(n);i++)
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define pb push_back
#define int ll
#define each(i, a) for (auto &&i : (a))
using ll = long long;
using ld = long double;
using vi = vector<int>;
using vvi = vector<vi>;
using vs = vector<string>;
using vvs = vector<vs>;
using vd = vector<ld>;
using vvd = vector<vd>;
using vb = vector<bool>;
using vvb = vector<vb>;
using P = pair<int, int>;
using vp = vector<P>;
using int128 = __int128_t;//cin coutはできない
template <class T>
using greater_queue = priority_queue<T, vector<T>, greater<T>>;
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int lcm(int a,int b){return a / gcd(a, b) * b;};
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

template <class T>
void CVEC(const T &v) {
	int c = v.size() - 1;
	for (int i = 0; i < c; i++) cout << v[i] << ' ';
	if (c > -1) cout << v[c];
	cout << '\n';
}

#pragma endregion header

signed main(){
    int n, m; cin >> n >> m;
	set<int> a, b;
	rep(i,n){
		int t; cin >> t;
		a.insert(t);
	}
	rep(i,m){
		int t; cin >> t;
		b.insert(t);
	}
	for(int i = 1; i <= 1000; i++){
		bool isA = a.count(i);
		bool isB = b.count(i);
		if(isA && isB) continue;
		if(!isA && !isB) continue;
		cout << i << endl;
	}
}

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

int main() {
  int n, k, m;
  cin >> n >> k >> m;
  int s = 0;
  int A;
  for(int i = 0; i < n - 1; i++){
    cin >> A;
    s += A;
  }
  int B = n*m - s;
  if(B > k){
    cout << -1;
  }
  else if(B < 0){
    cout << 0;
  }
  else{
    cout << B;
  }
}


#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#include <functional>
#include <bitset>
#include <assert.h>
#include <unordered_map>
#include <fstream>
#include <ctime>
#include <complex>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 510000;
ll dy[8] = {1,-1,0,0,1,-1,1,-1};
ll dx[8] = {0,0,1,-1,1,-1,-1,1};
const double pi = acos(-1);
const double eps = 1e-10;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << "debug: " << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << "debug: " << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
const int mod = 1e9 + 7;
//const int mod = 998244353;

template <std::uint_fast64_t Modulus> class modint {
  using u64 = std::uint_fast64_t;

public:
  u64 a;

  constexpr modint(const u64 x = 0) noexcept : a(x % Modulus) {}
  constexpr u64 &value() noexcept { return a; }
  constexpr const u64 &value() const noexcept { return a; }
  constexpr modint operator+(const modint rhs) const noexcept {
	return modint(*this) += rhs;
  }
  constexpr modint operator-(const modint rhs) const noexcept {
	return modint(*this) -= rhs;
  }
  constexpr modint operator*(const modint rhs) const noexcept {
	return modint(*this) *= rhs;
  }
  constexpr modint operator/(const modint rhs) const noexcept {
	return modint(*this) /= rhs;
  }
  constexpr modint &operator+=(const modint rhs) noexcept {
	a += rhs.a;
	if (a >= Modulus) {
	  a -= Modulus;
	}
	return *this;
  }
  constexpr modint &operator-=(const modint rhs) noexcept {
	if (a < rhs.a) {
	  a += Modulus;
	}
	a -= rhs.a;
	return *this;
  }
  constexpr modint &operator*=(const modint rhs) noexcept {
	a = a * rhs.a % Modulus;
	return *this;
  }
  constexpr modint &operator/=(modint rhs) noexcept {
	u64 exp = Modulus - 2;
	while (exp) {
	  if (exp % 2) {
		*this *= rhs;
	  }
	  rhs *= rhs;
	  exp /= 2;
	}
	return *this;
  }
};

using mint = modint<mod>;

ll modpow(ll x, ll n, ll mod){
	ll res = 1;
	while(n > 0){
		if(n & 1) res = res * x % mod;
		x = x * x % mod;
		n >>= 1;
	}
	return res;
}

int main(){
	int t; cin >> t;
	while(t--){
		ll n,a,b; cin >> n >> a >> b;
		if(n < a+b){
			cout << 0 << "\n";
			continue;
		}
		if(a > b) swap(a,b);
		mint ans = n * 2 - b * 2 - a + 3;
		ans *= a;
		mint t = (n-b+1) * (b-a-1) + mod;
		ans += t;
		ans *= ans;
		mint as = (n-a+1) * (n-b+1);
		as *= as;
		ans = as - ans;
		cout << ans.value() << "\n";
	}
}

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

int main(){
    std::fstream myfile("D:\\CodeBlocks\\c++\\input.txt.c", std::ios_base::in);
    ll n,sum=0;
    cin>>n;

    while(n--){
        ll a,b;
        cin>>a>>b;

        sum+=((b*(b+1)/2)-(a*(a-1)/2)) ;
    }
    cout<<sum;
    return 0;
}


//@formatter:off
#include<bits/stdc++.h>
#define overload4(_1,_2,_3,_4,name,...) name
#define rep1(i,n) for (ll i = 0; i < ll(n); ++i)
#define rep2(i,s,n) for (ll i = ll(s); i < ll(n); ++i)
#define rep3(i,s,n,d) for(ll i = ll(s); i < ll(n); i+=d)
#define rep(...) overload4(__VA_ARGS__,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep(i,n) for (ll i = ll(n)-1; i >= 0; i--)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define pb push_back
#define eb emplace_back
#define vi vector<int>
#define vvi vector<vector<int>>
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vd vector<double>
#define vvd vector<vector<double>>
#define vs vector<string>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define vp vector<P>
#define vvp vector<vector<P>>
#ifdef __LOCAL
#define debug(...) { cout << #__VA_ARGS__; cout << ": "; print(__VA_ARGS__); }
#else
#define debug(...) void(0)
#endif
#define INT(...) int __VA_ARGS__;scan(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;scan(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;scan(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;scan(__VA_ARGS__)
using namespace std;
using ll = long long;
using P = pair<int,int>;
using LP = pair<ll,ll>;
template<class S,class T> istream& operator>>(istream &is,pair<S,T> &p) { return is >> p.first >> p.second; }
template<class S,class T> ostream& operator<<(ostream &os,const pair<S,T> &p) { return os<<'{'<<p.first<<","<<p.second<<'}'; }
template<class T> istream& operator>>(istream &is,vector<T> &v) { for(T &t:v){is>>t;} return is; }
template<class T> ostream& operator<<(ostream &os,const vector<T> &v) { os<<'[';rep(i,v.size())os<<v[i]<<(i==int(v.size()-1)?"":","); return os<<']'; }
void Yes(bool b) { cout << (b ? "Yes" : "No") << '\n'; }
void YES(bool b) { cout << (b ? "YES" : "NO") << '\n'; }
template<class T> void fin(T a) { cout << a << '\n'; exit(0); }
template<class T> bool chmin(T& a,T b) {if(a > b){a = b; return true;} return false;}
template<class T> bool chmax(T& a,T b) {if(a < b){a = b; return true;} return false;}
void scan(){}
template <class Head, class... Tail> void scan(Head& head, Tail&... tail){ cin >> head; scan(tail...); }
template<class T> void print(const T& t){ cout << t << '\n'; }
template <class Head, class... Tail> void print(const Head& head, const Tail&... tail){ cout<<head<<' '; print(tail...); }
const int inf = 1001001001;
const ll linf = 1001001001001001001;
//@formatter:on

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    INT(n, m);
    vvp G(n);
    vi a(m), b(m);
    rep(i, m) {
        scan(a[i], b[i]);
        a[i]--;
        b[i]--;
    }
    vi c(n);
    cin >> c;
    vi ans(m, -1);
    int cnt = 0;
    auto direct = [&](int id, int from, int to) {
        if (a[id] == from) ans[id] = 0;
        else ans[id] = 1;
    };
    rep(i, m) {
        if (c[a[i]] > c[b[i]]) direct(i, a[i], b[i]);
        else if (c[a[i]] < c[b[i]]) direct(i, b[i], a[i]);
        else {
            G[a[i]].eb(b[i], i);
            G[b[i]].eb(a[i], i);
            cnt++;
        }
    }
    vb seen(n);
    auto dfs = [&](auto &self, int u, int p) -> void {
        seen[u] = true;
        for (auto[v, id] : G[u]) {
            if (v == p) continue;
            if (ans[id] < 0) direct(id, u, v);
            if (!seen[v]) {
                self(self, v, u);
            }
        }
    };
    rep(i, n) {
        if (seen[i]) continue;
        dfs(dfs, i, -1);
    }
    rep(i, m) {
        assert(ans[i] >= 0);
        cout << (ans[i] ? "<-" : "->") << endl;
    }
}

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

long long n,m,a[5005],b[5005],c[5005];
vector<int> grafo[105];
map<pair<int,int>,bool> f;
bool vis[101];

void dfs(int nodo){
	if(vis[nodo])return;
	vis[nodo]=true;

	for(auto i : grafo[nodo]){
		if(c[i]<c[nodo] || (c[i]==c[nodo] && f[{i,nodo}]==false && f[{nodo,i}]==false)){
			f[{nodo,i}]=true;
			dfs(i);
		}
	}
}

int main(){

	ios::sync_with_stdio(false);
	cin.tie(0);

	cin>>n>>m;

	for(int i=0;i<m;i++){
		cin>>a[i]>>b[i];
		grafo[a[i]].push_back(b[i]);
		grafo[b[i]].push_back(a[i]);
	}

	for(int i=1;i<=n;i++)cin>>c[i];

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

	for(int i=0;i<m;i++){
		if(f[{a[i],b[i]}])cout<<"->";
		else cout<<"<-";
		cout<<"\n";
	}

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl '\n'
int main (){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    ll n;cin>>n;
    vector<ll>a(n),b(n);

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

//    for(int i=n-1;i>=0;i--){
//        suff_b[i]=max(suff_b[i+1],b[i]);
//    }
    ll mx_a = 1, mx_b = 1,pr=1;
    for(int i=0;i<n;i++){
        mx_a=max(mx_a,a[i]);
        cout<<max(pr,mx_a*b[i])<<endl;
        pr = max(pr,mx_a*b[i]);
    }
    return 0;
}

#include <iostream>
#include <algorithm>
#include <string>
#include <complex>
#include <vector>
#include <set>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <bitset>
#include <numeric> //lcm
#include <iomanip> //double精度 setprecision

#include <chrono>
#include <random>
#include <cassert>

//#include <atcoder/all>

using namespace std;
//using namespace atcoder;

#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = (n)-1; i >= 0; --i)
#define rep1(i,n) for(int i = 1; i <= (n); ++i)
#define rrep1(i,n) for(int i = (n); i >= 1; --i)
#define REP(i,n,m) for(int i = (n); i < (m); ++i)
#define all(vec) (vec).begin(),(vec).end()

#define debug(a) { cerr << #a << " = " << a << endl;}
#define debugV(vec) { cerr << #vec << " : "; for(auto v : vec) cerr << v << " "; cerr << endl; }
#define debug2D(vec2D, w) { cerr << #vec2D << endl;  for(auto vec : vec2D) { for (auto v : vec) cerr << setw(w) << v << " "; cerr << endl; } }
#define debugVP(vec) { cerr << #vec << " : ";  for(auto v : vec) cerr << "(" << v.first << "," << v.second << ") "; cerr << endl;}
#define debug2DP(vec2D) { cerr << #vec2D << endl;  for(auto vec : vec2D) { for (auto v : vec) cerr << "(" << v.first << "," << v.second << ") "; cerr << endl; } }

typedef long long ll;

constexpr ll INF = 1e14; //32 ~2*10^10 //64 ~9*10^19
//constexpr ll MOD = 998244353;
constexpr ll MOD = 1000000007;
const double EPS = round(1e-6);
const char en = '\n';

/*
struct Edge {
	Edge(int _s, int _t, ll _cost = 1) : from(_s), to(_t), cost(_cost) {};
	int from, to;
	ll cost;
	//ll fee;
};
*/
//typedef ll Edge;7
struct Edge {
	int id;
	int from, to;

	Edge() { id = from = to = -1; };
	Edge(int a, int b, int c) : id(a), from(b), to(c) {};
};
typedef vector<vector<Edge>> Graph;
/*
void add_edge(Graph& g, int from, int to, ll cost = 1) {
	g[from].push_back(Edge(from, to, cost));
}
*/
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } else return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } else return false; }

void solve() {
	ll n; cin >> n;
	vector<ll> a(n), b(n);
	vector<ll> ma(n), mb(n);

	rep(i, n) cin >> a[i];
	rep(i, n) cin >> b[i];
	rep(i, n) { ma[i] = a[i]; if (i-1 >= 0) chmax(ma[i], ma[i-1]);}

	ll ans = 0;

	rep(i, n) {
		chmax(ans,a[i]*b[i]);
		if (i - 1 >= 0) chmax(ans,ma[i-1LL]*b[i]);

		cout << ans << endl;
	}

}

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

	//rep(i,3)
	solve();

}


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

void solve()
{

    ll int n;
    cin>>n;
    ll int arr[n];

    ll int count=0;

    unordered_map<ll int,ll int> m;
    for(ll int i=0;i<n;i++)
    {
        cin>>arr[i];

        if(arr[i]>=200)
        {
            m[arr[i]%200]++;
        }
        else
        {
            m[arr[i]]++;
        }
    }

    for(auto i:m)
    {
        ll int x=i.second;
        if(x>1)
        {
            count+=(x*(x-1)/2);
        }
    }

    cout<<count<<endl;

}

 int main()
 {
    // ll int t;
    // cin>>t;

    // while(t--)
    // {
    //     solve();
    // }

    solve();

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rrep(i, k, n) for (int i = k; i < (int)(n); i++)
#define repd(i, n) for (int i = n-1; i >= 0; i--)
#define rrepd(i, k, n) for (int i = n-1; i >= (int)(k); i--)
#define all(x) (x).begin(),(x).end()
#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
#define F first //pairの一つ目の要素
#define S second //pairの二つ目の要素
#define PB push_back //挿入
#define MP make_pair //pairのコンストラクタ
//V,Pは大文字i,l,bは小文字
using ll = long long;
using Vi = vector<int>;
using VVi = vector<Vi>;
using Vl = vector<ll>;
using VVl = vector<Vl>;
using Vb = vector<bool>;
using VVb = vector<Vb>;
using P = pair<int,int>;
using Pl = pair<ll, ll>;
using Vs = vector<string>;
const ll mod = 1000000007;
const ll inf = 1000000000000000000;//10の18乗
#define yn {puts("Yes");}else{puts("No");}
#define dame { puts("-1"); return 0;}

int main() {
    ll n;
    cin >> n;
    ll ans=0;
    Vl v(n);
    rep(i,n) cin >> v[i];
    Vl cnt(250);
    rep(i,n) cnt[(v[i])%200]++;
    rep(i,250){
        ans+=cnt[i]*(cnt[i]-1)/2;
    }
    cout << ans << endl;
}


#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <iomanip>
#include <algorithm>
#include <iterator>
#include <stack>
#include <queue>
#include <unordered_set>
#include <stdio.h>
#include <math.h>
#include <bitset>

using namespace std;
#define pb push_back
#define mp make_pair
#define ifor(a, b) for(int i = a; i < b; ++i)
#define jfor(a, b) for(int j = a; j < b; ++j)
#define kfor(a, b) for(int k = a; k < b; ++k)
#define irof(a, b) for(int i = b - 1; i >= a; --i)
#define jrof(a, b) for(int j = b - 1; j >= a; --j)
#define krof(a, b) for(int k = b - 1; k >= a; --k)
#define all(a) a.begin(), a.end()
#define safe_ind(ind, mass) ((ind) >= 0 ? mass[ind] : 0)

typedef long long ll;
typedef unsigned long long ull;

ll mmod(ll x, ll y) {
	if (x >= 0LL)
		return x % y;
	else
		return (y - (-x) % y) % y;
}

ll ddiv(ll x, ll y) {
	x -= mmod(x, y);
	return x / y;
}

struct edge {
	int u;
	int v;
	double weight;
	edge(int u, int v, double weight) :u(u), v(v), weight(weight) {}
};

double sosize(pair<int, int>& u, pair<int, int>& v) {
	return sqrt((u.first - v.first) * (u.first - v.first) + (u.second - v.second) * (u.second - v.second));
}

vector<int> dsu_par;
vector<int> dsu_size;

void dsu_init(int n) {
	dsu_par.resize(n);
	ifor(0, n) dsu_par[i] = i;
	dsu_size.resize(n, 1);
}

int dsu_root(int u) {
	if (dsu_par[u] == u) return u;
	return dsu_par[u] = dsu_root(dsu_par[u]);
}

void dsu_merge(int u, int v) {
	u = dsu_root(u);
	v = dsu_root(v);
	if (u != v) {
		if (dsu_size[v] > dsu_size[u]) {
			swap(u, v);
		}
		dsu_par[v] = u;
		dsu_size[u] += dsu_size[v];
	}
}

void solve() {
	int n; cin >> n;
	vector<pair<int, int>> dots;
	ifor(0, n) {
		int x, y;
		cin >> x >> y;
		dots.emplace_back(x, y);
	}
	vector<edge> edges;
	ifor(0, n) {
		edges.emplace_back(i, n, 100 - dots[i].second);
		edges.emplace_back(i, n + 1, dots[i].second + 100);
	}
	ifor(0, n - 1) {
		jfor(i + 1, n) {
			edges.emplace_back(i, j, sosize(dots[i], dots[j]));
		}
	}
	sort(all(edges), [](edge& f, edge& s) {
		return f.weight < s.weight;
	});
	dsu_init(n + 2);
	for (auto& it : edges) {
		dsu_merge(it.u, it.v);
		if (dsu_root(n) == dsu_root(n + 1)) {
			cout << fixed;
			cout << setprecision(8) << it.weight / 2 << "\n";
			return;
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	int t = 1;
	kfor(0, t)
		solve();
	//system("pause");
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define INCANT cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(12)
const int INF = 1e9 + 7;
const ll LINF = 1e18 + 7;
const int MOD = 1e9 + 7;
const double EPS = 1e-9;
void debug_out();
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T);
#ifdef MY_DEBUG
#define dbg(...) debug_out(__VA_ARGS__)
#define dbgs(x) cout << x << " "
#define dbge cout << endl
#else
#define dbg(...)
#define dbgs(x)
#define dbge
#endif
template <class T> bool chmax(T &, const T &);
template <class T> bool chmin(T &, const T &);
template <class T> T pwr(T, ll);
template <class T> T squ(T);
ll fact(ll);
ll comb(ll, ll);

int main() {
    INCANT;

    int n;
    cin >> n;
    vector<pair<int, int>> x(n), y(n);
    vector<pair<int, pair<int, int>>> ls(4);
    for (int i = 0; i < n; i++) {
        cin >> x[i].first >> y[i].first;
        x[i].second = i, y[i].second = i;
    }
    sort(x.begin(), x.end());
    reverse(x.begin(), x.end());
    sort(y.begin(), y.end());
    reverse(y.begin(), y.end());

    ls[0].first = x[0].first - x[n-1].first;
    ls[1].first = max(x[1].first - x[n-1].first, x[0].first - x[n-2].first);
    ls[2].first = y[0].first - y[n-1].first;
    ls[3].first = max(y[1].first - y[n-1].first, y[0].first - y[n-2].first);

    set<int> s1, s2;
    s1.insert(x[0].second), s1.insert(x[n-1].second);
    s2.insert(y[0].second), s2.insert(y[n-1].second);
    if (s1 == s2) {
        cout << max(ls[1].first, ls[3].first) << endl;
    }
    else {
        sort(ls.begin(), ls.end());
        reverse(ls.begin(), ls.end());
        cout << ls[1].first << endl;
    }
}

/*

-----------------------------------以下関数宣言------------------------------------ */

void debug_out() {
    cout << endl;
}

template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) {
    cout << H << " ";
    debug_out(T...);
}

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

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

template <class T> T pwr(T x, ll n) {
    T ans = 1;
    for (int i = 0; i < n; i++) {
        ans *= x;
    }
    return ans;
}

template <class T> T squ(T x) {
    return x * x;
}

ll fact(ll n) {
    ll res = 1;
    for (ll i = 1; i <= n; i++) res *= i;
    return res;
}

ll comb(ll n, ll r) { // comb(60, 30)までオーバーフローなし
    ll res = 1;
    for (int i = 1; i <= r; i++) {
        res *= n--;
        res /= i;
    }
    return res;
}


#include <bits/stdc++.h>
using namespace std;
int _ = (cout << fixed << setprecision(9), cin.tie(0), ios::sync_with_stdio(0));
using Int = long long;
int main() {
    int N; cin >> N;
    vector<int> A(N); for (auto &a : A) cin >> a;
    for (int i = 1; i < N; i += 2) {
        A[i] *= -1;
    }
    vector<Int> S(N + 1);
    for (int i = 0; i < N; i++) {
        S[i + 1] = S[i] + A[i];
    }
    map<Int, int> M;
    for (int i = 0; i < N + 1; i++) {
        M[S[i]]++;
    }
    Int ans = 0;
    for (auto [p, q] : M) {
        ans += (Int)q * (q - 1) / 2;
    }
    cout << ans << '\n';
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define mk make_pair
#define MOD 1000000007
#define pi 3.1415926536
/* BAAP BAAP HOTA HAI
   AUTHOR- Devansh Nandasana*/
void adde(vector<ll> adj[],ll u,ll v)
{
  adj[u].pb(v);
  adj[v].pb(u);
}
ll modInverse(ll a, ll m)
{
    ll m0=m;
    ll y=0,x=1;
    if(m==1)
      return 0;
    while(a>1)
    {
        ll q=a/m;
        ll t=m;
        m=a%m,a=t;
        t=y;
        y=x-q*y;
        x=t;
    }
    if(x<0)
      x+=m0;
    return x;
}
void BFS(vector<ll> adj[],ll bfs[],ll s,ll n)
{
    bool *visited = new bool[n+1];
    for(ll i=0;i<n+1;i++)
        visited[i] = false;
    list<ll> queue;
    visited[s] = true;
    bfs[s]=0;
    queue.push_back(s);
    vector<ll>::iterator i;
    while(!queue.empty())
    {
        s=queue.front();
        queue.pop_front();
        for(i=adj[s].begin();i!=adj[s].end();++i)
        {
            if(!visited[*i])
            {
                visited[*i] = true;
                bfs[*i]=bfs[s]+1;
                queue.push_back(*i);
            }
        }
    }
}
ll nCrModp(ll n,ll r,ll p)
{
    if (r > n - r)
        r = n - r;
    ll C[r + 1];
    memset(C, 0, sizeof(C));
    C[0] = 1;
    for (ll i = 1; i <= n; i++) {
        for (ll j = min(i, r); j > 0; j--)
            C[j] = (C[j] + C[j - 1]) % p;
    }
    return C[r];
}
ll find_center(ll n,vector<ll> adj[])
{
  queue<ll> q;
  bool vis[n+1];
  ll cnt[n+1];
  for(ll i=1;i<=n;i++)
  {
    vis[i]=false;
    cnt[i]=adj[i].size();
    if(cnt[i]==1)
    q.push(i);
  }
  while(q.size()>1)
  {
    ll cur=q.front();
    vis[cur]=true;
    q.pop();
    for(ll i=0;i<adj[cur].size();i++)
    {
      if(!vis[adj[cur][i]])
      {
        cnt[adj[cur][i]]--;
        if(cnt[adj[cur][i]]==1)
        q.push(adj[cur][i]);
      }
    }
  }
  return q.front();
}
int main()
{
  #ifndef ONLINE_JUDGE
    freopen("/home/devansh/Desktop/temp/input.txt", "r", stdin);
    freopen("/home/devansh/Desktop/temp/output.txt", "w", stdout);
  #endif
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ll n;
  cin>>n;
  ll a[n+1];
  for(ll i=1;i<=n;i++)
    cin>>a[i];
  ll dp[n+1];
  dp[n]=1e18;
  for(ll i=n-1;i>=0;i--)
  {
    dp[i]=a[i+1]-dp[i+1];
  }
  map<ll,ll> m;
  ll ans=0;
  for(ll i=0;i<=n;i++)
    m[dp[i]]++;
  for(auto [i,val]:m)
  {
    ans+=(val*(val-1)/2);
    if(i!=0 && i>0)
      ans+=(m[i]*m[-i]);
    // cout<<ans<<"\n";
  }
  cout<<ans<<"\n";
  return 0;
}


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

typedef long long ll;
#define rep(i,n) rep2(i,0,n)
#define rep2(i,l,r) for(ll i=(l),i##_len=(r);i<i##_len;i++)
const ll INF = 1LL << 60;

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

template <typename T>class segtree{
    typedef function<T(T,T)> F;
    const T _e;
    F fun1,fun2;
    public:
        ll _n;
        vector<T> node;
        //Constructor
        segtree():_n(0){}
        segtree(F resultFunction,ll n,T e):segtree(resultFunction,vector<T>(n,e),e,NULL){}
        segtree(F resultFunction,vector<T> &v,T e):segtree(resultFunction,v,e,NULL){}
        segtree(F resultFunction,vector<T> &v,T e,F changeFunction):fun1(resultFunction),_e(e),fun2(changeFunction){
            ll m=v.size();
            _n=1;
            while(_n<m) _n*=2;
            node.resize(2*_n-1);
            for(ll i=0;i<2*_n-1;i++){
                if(_n-1<=i&&i<_n+m-1) node[i]=v[i-_n+1];
                else node[i]=e;
            }
        }

        //Build//O(N)
        void build(){
            for (ll i = _n - 2; i>= 0; i--){
                node[i] = fun1(node[2 * i + 1], node[2 * i + 2]);
            }
        }

        //Update//O(logN)
        void update(ll num,T x,bool mode){
            num+=_n-1;
            if(mode) node[num]=fun2(node[num],x);
            else node[num]=x;
            while(num>0){
                num=(num-1)/2;//parent
                node[num]=fun1(node[num*2+1],node[num*2+2]);
            }
        }

        //Query//O(logN)
        T query(ll a,ll b){return query_sub(a,b,0,0,_n);}
        T query_sub(ll a,ll b,ll k,ll l,ll r){
            if(r<=a||b<=l) return _e;
            else if(a<=l&&r<=b) return node[k];
            else{
                T vl=query_sub(a,b,2*k+1,l,(l+r)/2);
                T vr=query_sub(a,b,2*k+2,(l+r)/2,r);
                return fun1(vl,vr);
            }
        }
};

int f(int a,int b){return a xor b;}

int main(){
    ll n,q;cin>>n>>q;
    vector<int> a(n);rep(i,n) cin>>a[i];
    segtree<int> seg(f,a,0,f);
    seg.build();

    rep(i,q){
        int t,x,y;cin>>t>>x>>y;
        x--;
        if(t==1) seg.update(x,y,1);
        else cout<<seg.query(x,y)<<endl;
    }
}

// Problem : F - Range Xor Query
// Contest : AtCoder - AtCoder Beginner Contest 185
// URL : https://atcoder.jp/contests/abc185/tasks/abc185_f
// Memory Limit : 1024 MB
// Time Limit : 3000 ms
// Powered by CP Editor (https://github.com/cpeditor/cp-editor)

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

#define SPEED ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
#define endl '\n'
#define vi vector<ll>
#define pii pair<ll, ll>
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define fill(a,b) memset(a, b, sizeof(a))
#define setbits(x) __builtin_popcountll(x)

const ll inf=0x3f3f3f3f3f3f3f3f, N = 3e5 + 5;
ll a[N], st[4 * N], n, q;
void build(ll node, ll L, ll R) {
	if(L == R) {
		st[node] = a[L];
		return;
	}
	ll M = (L + R)>>1;
	build(2 * node, L, M);
	build(2 * node + 1, M + 1, R);
	st[node] = st[2 * node] ^ st[2 * node + 1];
}
void update(ll node, ll L, ll R, ll pos, ll y) {
	if(pos < L || pos > R)return;
	if(L == R) {
		a[L] ^= y;
		st[node] ^= y;
		return;
	}
	ll M = (L + R)>>1;
	update(2 * node, L, M, pos, y);
	update(2 * node + 1, M + 1, R, pos, y);
	st[node] = st[2 * node] ^ st[2 * node + 1];
}
ll query(ll node, ll L, ll R, ll l, ll r) {
	if(L > r || l > R)return 0;
	if(l <= L && r >= R)return st[node];
	ll M = (L + R)>>1;
	return (query(2 * node, L, M, l, r) ^ query(2 * node + 1, M + 1, R, l, r));
}
int main() {
    SPEED;
    cin>>n>>q;
    for(ll i = 1; i <= n; i++)cin>>a[i];
    build(1, 1, n);
    while(q--) {
    	ll t, x, y;
    	cin>>t>>x>>y;
    	if(t == 1)update(1, 1, n, x, y);
    	else cout<<query(1, 1, n, x, y)<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<vector<int>> vvi;
typedef vector<vector<long long>> vvl;

int main(){
  int n,m;
  cin >> n >> m;
  vl h(n),w(m),a(n),s(n);
  rep(i,n)cin >> h[i];
  rep(i,m)cin >> w[i];
  sort(h.begin(),h.end());
  sort(w.begin(),w.end());
  for(int i=0;i<n-1;i++){
    a[i]=h[i+1]-h[i];
    if(i==0 or i==1) s[i]=a[i];
    else s[i]=s[i-2]+a[i];
  }
  ll ans=1e14;
  if(n==1){
    rep(i,m) ans=min(ans,abs(h[0]-w[i]));
  }else rep(i,m){
    //cout << ans << "\n";
    int insert=lower_bound(h.begin(),h.end(),w[i])-h.begin();
    int counter;
    if(insert%2==0){
      if(insert==0) ans=min(ans,(h[0]-w[i])+s[n-2]);
      else if(insert==n-1) ans=min(ans,s[n-3]+(h[n-1]-w[i]));
      else ans=min(ans,s[insert-2]+(h[insert]-w[i])+(s[n-2]-s[insert-1]));
    }else{
      if(insert==n) ans=min(ans,(w[i]-h[n-1])+s[n-3]);
      else if(insert==1) ans=min(ans,(w[i]-h[0])+s[n-2]);
      else ans=min(ans,s[insert-3]+(w[i]-h[insert-1])+(s[n-2]-s[insert-2]));
    }
  }
  cout << ans;
  return 0;
}

 //
#include<bits/stdc++.h>

using namespace std;

#define PB push_back
#define f fiCrst
#define s second
#define what_is(x) cerr << #x << " is " << x << endl;

typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;

const int INF = 1000000007;
const ll MOD = 1000000007;

void solve_test()
{
    int n, m;
    cin >> n >> m;
    ll h[n+1];
    h[0] = -INF;
    ll tot = 0;
    for(int i=1; i<=n; i++)
    {
        cin >> h[i];
        tot += h[i];
    }
    sort(h+1, h+n+1);
    ll sum[n+1][2];
    memset(sum, 0, sizeof(sum));
    sum[1][1] = h[1];
    for(int i=2; i<=n; i++)
    {
        for(int j=0; j<2; j++)
        {
            sum[i][j] = sum[i-1][j];
        }
        sum[i][i%2] += h[i];
    }
    ll ans = 1e18;
    for(int i=0; i<m; i++)
    {
        ll x;
        cin >> x;
        int ind = upper_bound(h, h+n+1, x) - h;
        ll sum1 = sum[ind-1][ind%2];
        sum1 += sum[n][(ind+1)%2] - sum[ind-1][(ind+1)%2];
        ll sum2 = tot - sum1;
        sum1 += x;
//        what_is(x);
//        what_is(sum1);
//        what_is(sum2);
        ans = min(ans, abs(sum1-sum2));
    }
    cout << ans;
}

signed main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);
    int tests;
    tests = 1;
    //cin >> tests;
    while(tests--)
    {
        solve_test();
    }
    return 0;
}


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

int main() {
    string ans = "No";
    string N;
    cin >> N;
    for (int i = 0; i <= 9; i++) {
        string Nt = string(i, '0') + N;
        if (Nt.size() % 2 == 1) Nt.erase(Nt.begin() + Nt.size() / 2);
        string s1 = Nt.substr(0, Nt.size() / 2);
        string s2 = Nt.substr(Nt.size() / 2);
        reverse(s2.begin(), s2.end());
        if (s1.compare(s2) == 0) ans = "Yes";
    }
    cout << ans << endl;
}

#include "bits/stdc++.h"
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    long long a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, m = 0, n = 0, p = 0, q = 0, mod = 998244353, pi = 3.1415926535;
    string s1,s2;
    char moji;

    cin >> s1;
    while(s1.size())
    {
        if(s1.back()=='0')
        s1.pop_back();
      else
        break;
    }
    s2=s1;
    reverse(s1.begin(),s1.end());
    cout << (s1==s2?"Yes":"No") << endl;
    return 0;
}


#include <iostream>
#include <algorithm>

int main() {
    int n;
    int a[1001], b[1001];
    std::cin >> n;
    for(int i = 0; i < n; ++i) {
        std::cin >> a[i] >> b[i];
    }
    int min = 1000000;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int sum = std::max(a[i], b[j]);
            if (sum < min) min = sum;
            sum = std::max(b[i], a[j]);
            if (sum < min) min = sum;
        }
    }
    for (int i = 0; i < n; ++i) {
        int sum = a[i] + b[i];
        if (sum < min) min = sum;
    }
    std::cout << min << std::endl;
    return 0;
}

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

struct mount{string name; int height;};

int main()
{
    int n;
    cin >> n;
    mount m[n];
    rep(i, n) cin >> m[i].name >> m[i].height;

    int a1 = 0, a2 = -1, m1 = 0, m2 = 0;

    rep(i, n){
        if(m[i].height > m1){
            m2 = m1;
            m1 = m[i].height;
            a2 = a1;
            a1 = i;
        }
        else if(m[i].height > m2){
            m2 = m[i].height;
            a2 = i;
        }
    }

    cout << m[a2].name << endl;

    return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <utility>
#include <tuple>
#include <cctype>
#include <bitset>
#include <complex>
#include <cmath>
#include <array>
#include <numeric>
#include <cassert>
#include <memory>
#include <random>
#include <chrono>
using namespace std;
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3fLL
//#define MOD 998244353
#define MOD 1000000007
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pint;
typedef pair<ll,ll> pll;
typedef tuple<int,int,int> tint;
typedef vector<int> vint;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pint> vpint;
typedef vector<tint> vtint;
typedef vector<vint> vvint;
// int dx[8]={0,0,-1,1,1,1,-1,-1};
// int dy[8]={-1,1,0,0,1,-1,1,-1};
const int SIZE=50;
//↑templete
int si, sj;
int t[SIZE][SIZE] = {};
int p[SIZE][SIZE] = {};

string nowStr = "";
string bestStr = "";

bool usedTile[2500] = {};
int score = 0;
int bestScore = 0;

int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
string com[4] = {"L", "D", "R", "U"};
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
chrono::system_clock::time_point start;
bool isEnd = 0;
void DFS(int x, int y){
    if (isEnd)
        return;
    int nowTime = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - start).count();

    if (nowTime > 100)
    {
        isEnd = 1;
        // cout << bestStr << endl;
        return;
    }

    //現在位置が入力される
    //マスを埋めて、スコアを加算する
    int tile = t[x][y];
    if (usedTile[tile])
        return;
    score += p[x][y];
    usedTile[tile] = 1;
    if (bestScore < score)
    {
        bestScore = score;
        bestStr = nowStr;
        // cout<<bestScore <<" "<< bestStr<< " " <<nowTime<<endl;
    }

    //探索順をランダムに決めてみる
    vint ran = {0, 1, 2, 3};
    shuffle(ran.begin(), ran.end(), engine);
    for (int a=0;a<4;a++)
    {
        int k = ran[a];
        //コマンドを作って次のマスに
        int X = x + dx[k], Y = y + dy[k];
        // cout << X <<" "<< Y <<endl;
        if (X < 0 || SIZE <= X || Y < 0 || SIZE <= Y)
            continue;
        nowStr += com[k];
        DFS(X, Y);
        nowStr.pop_back();
    }

    //全方向見たら、マスを開放してスコアを減算する
    score -= p[x][y];
    usedTile[tile] = 0;
    return;
}
signed main(){
    start = chrono::system_clock::now();
    cin>>si>>sj;
    for (int i=0;i<SIZE;i++)
        for (int j=0;j<SIZE;j++)
            cin>>t[i][j];
    for (int i=0;i<SIZE;i++)
        for (int j=0;j<SIZE;j++)
            cin>>p[i][j];

    int ret = 0;
    string retStr = "";
    for (int i=0;i<19;i++)
    {
        start = chrono::system_clock::now();
        bestScore = 0;
        score = 0;
        bestStr = "";
        nowStr = "";
        usedTile[2500] = {};
        isEnd = 0;
        DFS(si, sj);
        // cout << bestScore << endl;

        if (ret < bestScore)
        {
            ret = bestScore;
            retStr = bestStr;
        }
    }
    cout << retStr << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using st = string;
using ll = long long;
using ld = long double;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
using vs = vector<string>;
using vi = vector<int>;
using vd = vector<double>;
using vb = vector<bool>;
const ll MOD = 1000000007;
const ll INF_I = 0x3fffffff;
const ll INF_L = 0x7fffffffffffffff;
const ld PI = 3.141592653589793;
const st Y = "Yes", N = "No";
#define rep(i, n) for (ll i = 0; i < n; i++)
#define Mod(x, mod)                               \
	if (x < 0)                                    \
		x = (x + mod * (abs(x) / mod + 1)) % mod; \
	else                                          \
		x %= mod;
#define ExactMinority(degits) \
	cout << fixed << setprecision(degits)
#define UniqueVector(vec)         \
	sort(vec.begin(), vec.end()); \
	vec.erase(unique(vec.begin(), vec.end()), vec.end())
#define all(x) x.begin(), x.end()
#define deb(a) cout << "//" << a << endl;
ll Permutation(ll x, ll y)
{
	ll ret = 1;
	for (ll i = x - y + 1; i <= x; i++)
	{
		ret *= i;
	}
	return ret;
}
ll Combination(ll x, ll y)
{
	return Permutation(x, y) / Permutation(y, y);
}
ll Gcd(ll x, ll y)
{
	if (x < y)
	{
		swap(x, y);
	}
	if (x % y != 0)
	{
		return Gcd(y, x % y);
	}
	else
	{
		return y;
	}
}
ll Lcm(ll x, ll y)
{
	return x / Gcd(x, y) * y;
}

/////////////////////////////////////////////////////////bebebe
int main()
{
	int n, k;
	cin >> n >> k;
	vi a(n);
	vector<vector<int>> t(n, vector<int>(n));
	rep(i, n)
	{
		a[i] = i;
		rep(j, n)
		{
			cin >> t[i][j];
		}
	}
	ll time;
	ll count = 0;
	do
	{
		if (a[0] == 0)
		{
			time = 0;
			//cout << "[";
			rep(i, n - 1)
			{
				time += t[a[i]][a[i + 1]];
				//cout << t[i][a[i + 1]] << " ";
			}
			time += t[a[n-1]][0];
			//cout << t[n - 1][0] << "]" << endl;
			if (time == k)
			{
				count++;
			}
			/*rep(i, n)
			{
				cout << a[i] << " ";
			}
			cout << endl
				 << "//" << time << endl;*/
		}

	} while (next_permutation(all(a)));
	cout << count << endl;
}


//------------ヘッダーインクルード------------
#include <stdio.h>
#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//------------型マクロ定義------------
typedef long l;
typedef long long ll;
#define ALL(v) (v).begin(), (v).end()
//------------forマクロ定義------------

//------------main------------

int main(){
  long long int N;
  cin >> N;
  vector<long long int> vec;

  for(long long int i = 1; i*i <= N; i++){
    if((N % i) == 0LL){
      vec.push_back(i);
      if(i*i != N)vec.push_back((long long int)(N / i));
    }
  }

  sort(vec.begin(), vec.end());
  for(auto v: vec)cout <<  v << endl;

  return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define For(i,n,k) for(int i=(n);i<(k);i++)
#define ALL(a)  (a).begin(),(a).end()
ll ans = 0;
int ReLu(int x){
    if(x >= 0) return x;
    else return 0;
}
void Main(){
    int x;
    cin >> x;
    cout << ReLu(x) << endl;
}
int main(){
    Main();
    /*
    東方風神録は神が出てくるので当然神ゲー
    */
    return 0;
}


#include <bits/stdc++.h>
// clang-format off
using namespace std; using ll=long long; using ull=unsigned long long; using pll=pair<ll,ll>; const ll INF=4e18;
void print0(){}; template<typename H,typename... T> void print0(H h,T... t){cout<<h;print0(t...);}
void print(){print0("\n");}; template<typename H,typename... T>void print(H h,T... t){print0(h);if(sizeof...(T)>0)print0(" ");print(t...);}
void perr0(){}; template<typename H,typename... T> void perr0(H h,T... t){cerr<<h;perr0(t...);}
void perr(){perr0("\n");}; template<typename H,typename... T>void perr(H h,T... t){perr0(h);if(sizeof...(T)>0)perr0(" ");perr(t...);}
void ioinit() { cout << fixed << setprecision(15); cerr<<fixed<<setprecision(6); ios_base::sync_with_stdio(0); cin.tie(0); }
// clang-format on

ll fibrest(ll x0, ll y0, ll n, bool isx) {
    ll iter = 0;
    vector<ll> fib = {x0, y0};
    ll x = x0;
    ll y = y0;
    ll op = 0;
    while (true) {
        if (isx) {
            x = x + y;
        } else {
            y = y + x;
        }
        if (x >= n) break;
        op++;
        isx = !isx;
    }
    return op;
}
void op(vector<ll> &ops, ll &x, ll &y, ll t) {
    if (t == 1) {
        x = x + 1;
    }
    if (t == 2) {
        y = y + 1;
    }
    if (t == 3) {
        x = x + y;
    }
    if (t == 4) {
        y = y + x;
    }
    ops.push_back(t);
}
void output(vector<ll> &ops) {
    ll k = ops.size();
    print(ops.size());
    for (auto ope : ops) {
        print(ope);
    }
}

int main() {
    ioinit();

    ll n;
    cin >> n;
    // while (fib.back() < n) {
    //     fib.push_back(fib[fib.size() - 1] + fib[fib.size() - 2]);
    // }
    // ll m = fib.size();

    ll x = 0;
    ll y = 0;

    vector<ll> ops;
    if (n < 120) {
        while (x < n) {
            op(ops, x, y, 1);
        }
        output(ops);
        return 0;
    }

    op(ops, x, y, 1);
    bool isx = false;
    while (true) {
        if (x + y > n) {
            while (x < n) {
                op(ops, x, y, 1);
            }
            break;
        }
        ll curop = fibrest(x, y, n, isx);

        {
            ll k = 0;
            while (true) {
                ll r = fibrest(x + k + 1, y, n, isx);
                if (r != curop) break;
                //perr(curop, r);
                op(ops, x, y, 1);
                k = k + 1;
            }
        }
        if (isx) {
            op(ops, x, y, 3);
        } else {
            op(ops, x, y, 4);
        }
        isx = !isx;
        if (x >= n) break;
    }
    output(ops);
}

#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < (n); i++)
using namespace std;

int main() {
	int n; cin >> n;
	vector<int> p(n), pos(n), res;
	REP(i, n) cin >> p[i], pos[--p[i]] = i;

	vector<bool> used(n-1, false);
	REP(i, n) {
		int now = pos[i];
		while (i < now) {
			int before = now - 1;
			if (used[before]) { cout << -1 << '\n'; return 0; }
			used[before] = true;
			pos[p[now]] = before;
			pos[p[before]] = now;
			swap(p[before], p[now]);
			res.emplace_back(before);
			now--;
		}
	}

	if ((int)res.size() != n-1) cout << -1 << '\n';
	else REP(i, n-1) cout << res[i] + 1 << '\n';
    return 0;
}


#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(a) a.begin(),a.end()
using namespace std;

int main() {
  int H,W;cin>>H>>W;
  vector<vector<bool> > Map(H+10,vector<bool>(W+10,false));//黒ならTRUE
  int sy=-1,sx=-1;
  for(int h=1;h<=H;h++){
    string s;cin>>s;
    for(int w=1;w<=W;w++){
      Map[h][w]=(s[w-1]=='#');
      if(Map[h][w]&&sy==-1){
        sy=h;sx=w;
      }
    }
  }
  if(sy==-1){
    cout<<0<<endl;
    return 0;
  }
  int ny=sy,nx=sx;
  int p=0;
  int r=2;//下から来た
  int i=0;
  while(true){
    //i++;
    r=-r;
    bool a1=Map[ny][nx];
    bool a2=Map[ny-1][nx];
    bool a3=Map[ny][nx-1];
    bool a4=Map[ny-1][nx-1];
    int k1,k2;
    if((a1?1:0)+(a2?1:0)+(a3?1:0)+(a4?1:0)==3){
      a1=!a1;a2=!a2;a3=!a3;a4=!a4;
    }
    if(a1&&!a2&&!a3&&!a4){k1=-2;k2=1;}
    if(!a1&&a2&&!a3&&!a4){k1=1;k2=2;}
    if(!a1&&!a2&&a3&&!a4){k1=-2;k2=-1;}
    if(!a1&&!a2&&!a3&&a4){k1=-1;k2=2;}
    if(a1&&a2&&!a3&&!a4){k1=-2;k2=2;}
    if(!a1&&!a2&&a3&&a4){k1=-2;k2=2;}
    if(!a1&&a2&&!a3&&a4){k1=-1;k2=1;}
    if(a1&&!a2&&a3&&!a4){k1=-1;k2=1;}
    int n=99;
    //cout<<a1<<a2<<a3<<a4<<endl;
    //cout<<k1<<" "<<k2<<endl;
    if(r==k1)n=k2;
    else if(r==k2)n=k1;
    if(-n!=r)p++;
    if(n==1)nx++;
    if(n==-1)nx--;
    if(n==2)ny--;
    if(n==-2)ny++;
    //cout<<p<<" "<<ny<<" "<<nx<<endl;

    r=n;
    if(ny==sy&&nx==sx)break;
    if(i>13)break;
  }
  cout<<p<<endl;
}

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

//#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#define pb push_back
#define fi first
#define se second
#define ll long long
#define tp top()
#define fr front()
#define vi vector<int>
#define sz size()
#define rep(i,a,b) for(int i = a; i < b; ++i)
#define mem(a,  b) memset(a,  (b),  sizeof(a))
#define clr(a) memset(a,  0,  sizeof(a))
#define sqr(x) ( (x) * (x) )
#define all(v) v.begin(),  v.end()

typedef pair<int, int> pii;
typedef pair<int,pii> pip;
typedef pair<pii,int> ppi;
typedef pair<pii,pii> ppp;

void base(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

vector<pair<double, double>> ps;

#define N 120
int par[N];
int fpar(int n){
	return par[n] = (par[n] == n)? n : fpar(par[n]);
}

double dist(pair<double, double> p1, pair<double, double> p2){
	return hypot(p1.fi-p2.fi, p1.se-p2.se);
}

void solve(){
	int n; cin>>n;
	rep(i,0,n){
		double x,y;cin>>x>>y;
		ps.pb({x,y});
		par[i]=i;
	}
	par[n]=n;
	par[n+1]=n+1;

	priority_queue<pair<double, pii>, vector<pair<double, pii>>, greater<pair<double, pii> > > pq;

	rep(i,0,n){
		pq.push({100-ps[i].se,{i,n}});
		pq.push({ps[i].se-(-100),{i,n+1}});
		rep(j,i+1,n){
			pq.push({dist(ps[i],ps[j]),{i,j}});
		}
	}

	double ans = 0;

	while(pq.sz){
		double range = pq.tp.fi;
		int x = pq.tp.se.fi;
		int y = pq.tp.se.se;
		pq.pop();

		int p1 = fpar(x);
		int p2 = fpar(y);
		if (p1 != p2) {
			par[p1] = p2;
			int pn = fpar(n);
			int pm = fpar(n+1);
			ans = range;
			if (pn == pm) break;
		}
	}

	cout<<fixed<<setprecision(9)<<ans/2.0<<"\n";
}

int main()
{
	base();
//  freopen("input.txt", "r", stdin);
//  freopen("output.txt", "w", stdout);
	int t=1;
//	cin>>t;
	while(t--){
		solve();
	}
	return 0;
}


#include<iostream>
#include<bits/stdc++.h>
#include<climits>
#include<cmath>
#include<set>

using namespace std;

long long binpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}

int main(){

     int n;
     cin>>n;
     if(floor(1.08*n)<206) cout<<"Yay!"<<endl;
     else if(floor(1.08*n)>206) cout<<":("<<endl;
     else cout<<"so-so"<<endl;

     return 0;

}

#include <bits/stdc++.h>

using namespace std;

#define rep(i,j,k) for(long long int i=(long long int)j;i<(long long int)k;i++)
#define MOD 1000000007
#define pb push_back
#define fi first
#define se second
typedef long long lld;
typedef long ld;
#define inf LLONG_MAX
const lld MAXN = (int)3e5 + 5;

typedef pair<lld, lld> pii;
ld gcd(ld a, ld b)
{
    if(b==0)
    return a;
    return gcd(b,a%b);
}
lld power(lld x, lld y)
{
    lld res = 1;
    while (y > 0) {

        if (y & 1)
            res = (res * x) % MOD;
        y = y >> 1;
        x = (x * x) % MOD;
    }
    return res;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    lld n;
    cin>>n;
    lld ans=n;
    map<lld,lld> m;
    rep(i,2,sqrt(n)+1)
    {
        lld j=i*i;
        while(j<=n)
        {
        m[j]++;

         if(m[j]==1)
         ans--;
//cout<<j<<endl;
          j*=i;
        }
    }
    cout<<ans<<endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
// #define ll long long
#define f(i,n) for(int i=0;i<n;i++)
#define fi(i,x,n) for(int i=x;i<n;i++)
#define pii pair<int,int>
#define vi vector<int>
#define pb push_back
#define rof(i,a,b) for(int i=(a);i>=(b);i--)
#define S second
#define F first
#define is insert
#define INF 1000000000
#define MOD 1000000007

void solve() {

	int n; cin >> n;

	vi a(n); f(i, n) cin >> a[i];

	vi cnt(100000, 0);

	int res = 0;

	for (int x : a)
	{
		int k = x % 200;
		res += cnt[k];
		cnt[k]++;
	}

	cout << res;

}

int32_t main() {
#ifndef ONLINE_JUDGE
	// for getting input from input.txt
	freopen("input.txt", "r", stdin);
	// for writing output to output.txt
	freopen("output.txt", "w", stdout);
#endif

	int t = 1;
	//cin >> t;
	while (t--)
	{
		solve();
		cout << "\n";
	}
}

#include <bits/stdc++.h>
#define M 1000000007
#define fio                           \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);
#define d(x) cout << #x << " " << x << "\n";
#define min(x1, x2) (x1 > x2 ? x2 : x1)
#define max(x1, x2) (x1 < x2 ? x2 : x1)
#define min3(x1, x2, x3) (x3 > min(x1, x2) ? min(x2, x1) : x3)
#define max3(x1, x2, x3) (x3 < max(x1, x2) ? max(x1, x2) : x3)
#define ll long long int
#define ul unsigned long long int
#define p pair<ll, ll>
#define ld long double
#define dv(v)                            \
    cerr << #v << "  ";                  \
    for (int i = 0; i < (v).size(); i++) \
        cerr << v[i] << " ";             \
    cerr << "\n";
#define inf INT_MAX
#define mp(x, y) make_pair(x, y)
using namespace std;

int main()
{
    fio;
    ll t, n, x, y, z, k;
    string s;
    cin >> s;
    n=0;
    for (int i = 0; i < s.size(); ++i)
    {
        string a;
        for (int j = i; j < min(s.size(), i + 4); ++j)
        {
            a.push_back(s[j]);
        }
        if (a == "ZONe")
        {
            ++n;
        }
    }
    cout<<n;
    return 0;
}


#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma,avx512f,avx512bw,avx512bitalg")
#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>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << " is " << x << endl

#define pub push_back
#define pob pop_back
#define puf push_front
#define pof pop_front
#define lb lower_bound
#define ub upper_bound

#define rep(x,start,end) for(int x=start;x!=end;x++)
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()

#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>
//change less to less_equal for non distinct pbds, but erase will bug

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

int B,m;
bool bad[25][25];

int ind[1050000];

int ahat[1050000][21];
int bhat[1050000][21];
ll hat[1050000][21];

void conv(){
	for (int x=0;x<1048576;x++) {
		ahat[x][__builtin_popcount(x)]=ind[x];
		bhat[x][__builtin_popcount(x)]=ind[x];
	}

	rep(bit,0,20){
		for (int x=0;x<1048576;x++) if (x&(1<<bit)){
			rep(cnt,0,21){
				ahat[x][cnt]+=ahat[x^(1<<bit)][cnt];
				bhat[x][cnt]+=bhat[x^(1<<bit)][cnt];
			}
		}
	}

	for (int x=0;x<1048576;x++){
		rep(cnt,0,21){
			rep(cnt2,0,cnt+1){
				hat[x][cnt]+=(ll)ahat[x][cnt2]*bhat[x][cnt-cnt2];
			}
		}
	}

	rep(bit,0,20){
		for (int x=0;x<1048576;x++) if (x&(1<<bit)){
			rep(cnt,0,21){
				hat[x][cnt]-=hat[x^(1<<bit)][cnt];
			}
		}
	}

    memset(ahat,0,sizeof(ahat));
	memset(bhat,0,sizeof(bhat));

	for (int x=0;x<1048576;x++){
		ahat[x][__builtin_popcount(x)]=ind[x];
		bhat[x][__builtin_popcount(x)]=hat[x][__builtin_popcount(x)];
	}

	memset(hat,0,sizeof(hat));

	rep(bit,0,20){
		for (int x=0;x<1048576;x++) if (x&(1<<bit)){
			rep(cnt,0,21){
				ahat[x][cnt]+=ahat[x^(1<<bit)][cnt];
				bhat[x][cnt]+=bhat[x^(1<<bit)][cnt];
			}
		}
	}

	for (int x=0;x<1048576;x++){
		rep(cnt,0,21){
			rep(cnt2,0,cnt+1){
				hat[x][cnt]+=(ll)ahat[x][cnt2]*bhat[x][cnt-cnt2];
			}
		}
	}

	rep(bit,0,20){
		for (int x=0;x<1048576;x++) if (x&(1<<bit)){
			rep(cnt,0,21){
				hat[x][cnt]-=hat[x^(1<<bit)][cnt];
			}
		}
	}
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin.exceptions(ios::badbit | ios::failbit);

	cin>>B>>m;

	int a,b;
	rep(x,0,m){
		cin>>a>>b;
		a--,b--;
		bad[a][b]=bad[b][a]=true;
	}

	ind[0]=1;
	rep(x,1,1<<B){
		int temp=__builtin_ctz(x);
		int nx=x^(1<<temp);

		ind[x]=ind[nx];

		rep(bit,0,B) if (nx&(1<<bit) && bad[temp][bit]){
			ind[x]=0;
		}
	}

	conv();

	cout<<hat[(1<<B)-1][B]<<endl;
}

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

using ll = long long;
using pii = pair<int, int>;
template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define rep(i, n) rep2(i, 0, n)
#define rep2(i, m, n) for (int i = m; i < (n); i++)
#define per(i, b) per2(i, 0, b)
#define per2(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define ALL(c) (c).begin(), (c).end()
#define SZ(x) ((int)(x).size())

constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }

template <class T, class U>
void chmin(T& t, const U& u) {
    if (t > u) t = u;
}
template <class T, class U>
void chmax(T& t, const U& u) {
    if (t < u) t = u;
}

template <class T, class U>
ostream& operator<<(ostream& os, const pair<T, U>& p) {
    os << "(" << p.first << "," << p.second << ")";
    return os;
}

template <class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "{";
    rep(i, v.size()) {
        if (i) os << ",";
        os << v[i];
    }
    os << "}";
    return os;
}

#ifdef LOCAL
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 << __LINE__ << " [" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

const ll INF = TEN(18);

int main() {
    int N, M;
    cin >> N >> M;
    V<ll> w(N);
    rep(i, N) cin >> w[i];

    V<int> pm(N);
    iota(ALL(pm), 0);
    V<pii> br(M);
    ll mx = 0;

    for (auto v : w) chmax(mx, v);
    rep(i, M) cin >> br[i].se >> br[i].fi;
    rep(i, M) if (mx > br[i].fi) {
        puts("-1");
        return 0;
    }

    map<int, int> D;

    int now = 0;
    V<int> xs;
    rep(i, 1 << N) {
        int s = 0;
        rep(j, N) if (i >> j & 1) { s += w[j]; }
        xs.pb(s);
    }
    sort(ALL(xs));
    sort(ALL(br));
    int md = 0;
    for (auto v : xs) {
        while (now < M && br[now].fi < v) {
            chmax(md, br[now++].se);
        }
        D[v] = md;
    }

    ll ans = INF;
    do {
        V<ll> a(N);
        rep(i, N) a[i] = w[pm[i]];
        V<ll> dp(N);

        rep(i, N) {
            int s = 0;
            if (i) chmax(dp[i], dp[i - 1]);
            for (int j = i; j < N; ++j) {
                s += a[j];
                if (j > i) chmax(dp[j], dp[i] + D[s]);
            }
        }
        chmin(ans, dp.back());
    } while (next_permutation(ALL(pm)));
    cout << ans << endl;
    return 0;
}