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

const int ac = 2e5 + 5, bc = (1 << 18);
ll PR[ac];
ll CS[ac];

struct Tree
{
	vector<ll> T;
	Tree()
	{
		T.resize(bc * 2);
	}
	void update(int a, ll b)
	{
		a += bc;
		T[a] = b;
		while (a)
		{
			a /= 2;
			T[a] = min(T[a * 2], T[a * 2 + 1]);
		}
	}
	ll query(int a, int b)
	{
		a += bc; b += bc;
		ll m = min(T[a], T[b]);
		while (a / 2 != b / 2)
		{
			if (a % 2 == 0) m = min(m, T[a + 1]);
			if (b % 2 == 1) m = min(m, T[b - 1]);
			a /= 2; b /= 2;
		}
		return m;
	}
};

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int n, q, a, b; cin >> n >> q >> a >> b; a--; b--;
	vector<ll> Q; Q.push_back(a);
	for (int i = 0; i < q; i++) { int x; cin >> x; x--; Q.push_back(x); }
	ll s = 0;
	for (int i = 1; i <= q; i++) CS[i] = abs(Q[i] - Q[i - 1]), s += CS[i];
	Tree t1, t2;
	for (int i = 0; i < n; i++) t1.update(i, (ll)1e12), t2.update(i, (ll)1e12);
	t1.update(b, b); t2.update(b, -b);
	for (int i = 1; i <= q; i++)
	{
		ll w = min(t2.query(0, Q[i]) + Q[i], t1.query(Q[i], n - 1) - Q[i]) - CS[i];
		if (w < t1.query(Q[i - 1], Q[i - 1]))
		{
			t1.update(Q[i - 1], w + Q[i - 1]);
			t2.update(Q[i - 1], w - Q[i - 1]);
		}
	}
	ll m = 1e18;
	for (int i = 0; i < n; i++)
		m = min(m, t1.query(i, i) - i);
	cout << m + s << '\n';
}

        #include <bits/stdc++.h>
        using namespace std;
   #define int long long
const int MAX = 510000;
const int MOD = 1000000007;
template <typename T,typename E>
struct SegmentTree{
  using F = function<T(T,T)>;
  using G = function<T(T,E)>;
  using H = function<E(E,E)>;
  int n,height;
  F f;
  G g;
  H h;
  T ti;
  E ei;
  vector<T> dat;
  vector<E> laz;
  SegmentTree(int n_,F f,G g,H h,T ti,E ei,vector<T> v=vector<T>()):
    f(f),g(g),h(h),ti(ti),ei(ei){
init(n_);
    if(n_==(int)v.size()) build(n_,v);

    }

  void init(int n_){
    n=1;height=0;
    while(n<n_) n<<=1,height++;
    dat.assign(2*n,ti);
    laz.assign(2*n,ei);
  }

  void build(int n_,const vector<T> &v){
    for(int i=0;i<n_;i++) dat[n+i]=v[i];
    for(int i=n-1;i;i--)
      dat[i]=f(dat[(i<<1)|0],dat[(i<<1)|1]);
  }

  inline T reflect(int k){
    return laz[k]==ei?dat[k]:g(dat[k],laz[k]);
  }

  inline void propagate(int k){
    if(laz[k]==ei) return;
    laz[(k<<1)|0]=h(laz[(k<<1)|0],laz[k]);
    laz[(k<<1)|1]=h(laz[(k<<1)|1],laz[k]);
    dat[k]=reflect(k);
    laz[k]=ei;
  }

  inline void thrust(int k){
    for(int i=height;i;i--) propagate(k>>i);
  }

  inline void recalc(int k){
    while(k>>=1)
      dat[k]=f(reflect((k<<1)|0),reflect((k<<1)|1));
  }

  void update(int a,int b,E x){
    if(a>=b) return;
    thrust(a+=n);
    thrust(b+=n-1);
    for(int l=a,r=b+1;l<r;l>>=1,r>>=1){
      if(l&1) laz[l]=h(laz[l],x),l++;
      if(r&1) --r,laz[r]=h(laz[r],x);
    }
    recalc(a);
    recalc(b);
  }

  void set_val(int a,T x){
    thrust(a+=n);
    dat[a]=x;laz[a]=ei;
    recalc(a);
  }

  T query(int a,int b){
    if(a>=b) return ti;
    thrust(a+=n);
    thrust(b+=n-1);
    T vl=ti,vr=ti;
    for(int l=a,r=b+1;l<r;l>>=1,r>>=1) {
      if(l&1) vl=f(vl,reflect(l++));
      if(r&1) vr=f(reflect(--r),vr);
    }
    return f(vl,vr);
  }

  template<typename C>
  int find(int st,C &check,T &acc,int k,int l,int r){
    if(l+1==r){
      acc=f(acc,reflect(k));
      return check(acc)?k-n:-1;
    }
    propagate(k);
    int m=(l+r)>>1;
    if(m<=st) return find(st,check,acc,(k<<1)|1,m,r);
    if(st<=l&&!check(f(acc,dat[k]))){
      acc=f(acc,dat[k]);
      return -1;
    }
    int vl=find(st,check,acc,(k<<1)|0,l,m);
    if(~vl) return vl;
    return find(st,check,acc,(k<<1)|1,m,r);
  }

  template<typename C>
  int find(int st,C &check){
    T acc=ti;
    return find(st,check,acc,1,0,n);
  }
};
 SegmentTree<int,int> seg(200003, [](int a,int b){return max(a,b);},
			   [](int a,int b){return b;},[](int a,int b){return b;},0,0);
     signed main(){
 int n,q;

 cin>>n>>q;
 int x[q+2],y[q+2]={},ans=0;
 for(int i=0;i<q+2;i++)cin>>x[i];

auto f = [&](int a,int z) -> int{
     if(a==0)return 0;
     return abs(z-x[q+2-a])+y[q+2-a];
};
for(int i=1;i<=q;i++){
     y[q+2-i]+=f(seg.query(x[q+1-i],x[q+1-i]+1),x[q+1-i])-abs(x[q+2-i]-x[q+1-i]);
     ans+=abs(x[q+2-i]-x[q+1-i]);
     int ok=x[q+1-i],ng,mid;
     if(x[q+2-i]>x[q+1-i]){
          ng=n+1;
          while(abs(ok-ng)>1){
               mid=(ok+ng)/2;
               if(f(i,mid)<=f(seg.query(mid,mid+1),mid))ok=mid;
               else ng=mid;
          }
          seg.update(x[q+1-i],ng,i);
     }else{
          ng=0;
          while(abs(ok-ng)>1){
               mid=(ok+ng)/2;
               if(f(i,mid)<=f(seg.query(mid,mid+1),mid))ok=mid;
               else ng=mid;
          }
          seg.update(ok,x[q+1-i],i);
     }

}
cout<<ans+f(seg.query(x[0],x[0]+1),x[0])<<endl;
 }


#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <cmath>
#include <set>
#include <algorithm>
#include <iomanip>

typedef long long ll;
const ll MOD = 1e9 + 7;
const long long INF = 1LL<<60;
const double PI=3.14159265358979323846;
const int NMAX=100005;
using namespace std;

int main(){
    int n;
    cin >> n;
    vector<vector<pair<int,int>>> a(n);
    for(int i = 0; i < n; i++){
        int an;
        cin >> an;
        for(int j = 0; j < an; j++){
            int x,y;
            cin >> x >> y;
            x--;
            a[i].push_back({x,y});
        }
    }

    int ans = 0;
    for(int i = 0; i < (2<<n); i++){
        vector<bool> honest(n,false);
        int cnt = 0;
        for(int j = 0; j < n; j++){
            if((i>>j) & 1){
                honest[j] = true;
                cnt++;
            }
        }

        for(int j = 0; j < n; j++){
            if(honest[j] == false) continue;
            for(int k = 0; k < a[j].size(); k++){
                int x = a[j][k].first;
                int y = a[j][k].second;
                if((honest[x] == false && y == 1) ||
                    (honest[x] == true && y == 0)){
                        cnt = -1;
                        break;
                    }
            }
            if(cnt == -1) break;
        }
        ans = max(ans, cnt);
    }

    cout << ans << endl;

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define REP(i,a,b) for(int i=a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)
#define all(c) (c).begin(), (c).end()
#define zero(a) memset(a, 0, sizeof a)
#define minus(a) memset(a, -1, sizeof a)
#define watch(a) { cout << #a << " = " << a << endl; }
template<class T1, class T2> inline bool minimize(T1 &a, T2 b) { return b < a && (a = b, 1); }
template<class T1, class T2> inline bool maximize(T1 &a, T2 b) { return a < b && (a = b, 1); }

typedef long long ll;
int const inf = 1<<29;

enum Face : int { Top, Front, Right, Left, Back, Bottom };
struct cube {
  int f[6];
  unordered_map<int, string> mp;
  cube(){}
  /*
            1(Top)
    4(Left) 2(Front) 3(Right) 5(Back)
            6(Bottom)
  */
  cube(vector<int> const& vs){ for(int i=0; i<6; i++) f[i] = vs[i]; }
  cube(vector<string> const& vs) { for(int i=0; i<6; i++) mp[i+1] = vs[i]; }
  void roll_z() { roll(1, 2, 4, 3); }
  void roll_y() { roll(0, 2, 5, 3); }
  void roll_x() { roll(0, 1, 5, 4); }
  void roll(int i, int j, int k, int l) {
    int t = f[i]; f[i] = f[j]; f[j] = f[k]; f[k] = f[l]; f[l] = t;
  }

  void roll(int k) {
    if(k == 0) roll_y();
    if(k == 1) roll_x();
    if(k == 2) for(int i=0; i<3; i++) roll_y();
    if(k == 3) for(int i=0; i<3; i++) roll_x();
  }

  bool roll_top_front(int top, int front) {
    for(int k = 0; k < 6; (k & 1 ? roll_y() : roll_x()), k++)
      for(int i = 0; i < 4; roll_z(), ++i)
        if(top == f[Top] && front == f[Front]) return true;
    return false;
  }

  bool operator== (cube const& rhs) const {
    for(int i=0; i<6; i++)
      if(f[i] != rhs.f[i]) return false;
    return true;
  }

  bool isomorphic(cube rhs) const {
    for(int k = 0; k < 6; (k & 1 ? rhs.roll_y() : rhs.roll_x()), k++)
      for(int i = 0; i < 4; rhs.roll_z(), ++i)
        if(operator==(rhs)) return true;
    return false;
  }

};

int main() {

  int N; cin >> N;
  vector<cube> cs(N); rep(i, N) rep(j, 6) cin >> cs[i].f[j];
  cout << ([&]() {
    rep(i, N) REP(j, i+1, N)
      if(cs[i].isomorphic(cs[j])) return false;
    return true;
  }() ? "Yes\n" : "No\n");

  return 0;
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

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

	vector<vector<ll>> cnt(62, vector<ll>(62, 0));
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		if (find(s.begin(), s.end(), '.') == s.end()) s.push_back('.');
		int pos = 0;
		while (s[pos] != '.') pos++;
		s += string(10 - s.size() + pos, '0');
		ll y = 0;
		for (auto c : s) {
			if (isdigit(c)) y = y * 10 + c - '0';
		}
		int p2 = 0, p5 = 0;
		for (; y % 2 == 0; y /= 2, p2++);
		for (; y % 5 == 0; y /= 5, p5++);
		cnt[p2][p5]++;
	}
	ll ans = 0;
	for (int p2 = 0; p2 < 62; p2++) {
		for (int p5 = 0; p5 < 62; p5++) {
			for (int pp2 = 0; pp2 < 62; pp2++) {
				for (int pp5 = 0; pp5 < 62; pp5++)
					ans += cnt[p2][p5] * cnt[pp2][pp5] * (min(p2 + pp2, p5 + pp5) >= 18) *
					       (pair<int, int>{p2, p5} != pair<int, int>{pp2, pp5});
			}
		}
	}
	for (int p2 = 0; p2 < 62; p2++) {
		for (int p5 = 0; p5 < 62; p5++) ans += cnt[p2][p5] * (cnt[p2][p5] - 1) * (min(p2, p5) * 2 >= 18);
	}
	cout << ans / 2 << '\n';
}

#include <bits/stdc++.h>
using namespace std;
template<class T> ostream& operator<<(ostream &os, vector<T> V) { os << "[ ";
  for(auto v:V)os << v << " "; return os << "]";
}
template<class T> ostream& operator<<(ostream &os, set<T> S){ os << "{ ";
  for(auto s:S) os<<s<<" ";  return os<<"}";
}
template<class L, class R> ostream& operator<<(ostream &os, pair<L,R> P) {
  return os<<"("<<P.first<<","<< P.second << ")";
}
template<class L, class R> ostream& operator<<(ostream &os, map<L,R> M) {
  os<<"{ ";for(auto m:M)os<<"("<<m.first<<":"<<m.second<<")";
  return os<<"}";
}
#define cerr cout
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...) 1
#endif
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// find_by_order(k)  returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;
//For multiset use less_equal operator but it does support erase operations for multiset
#define ll long long
#define ld long double
#define vll vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define I insert
#define pb push_back
#define F first
#define S second
#define endl "\n"
#define all(v) (v).begin(),(v).end()
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef pair<pii,int> ppi;
typedef vector<pii> vpii;
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define mp make_pair

const int mod = 1e9+7;

inline int add(int a,int b){a+=b;if(a>=mod)a-=mod; return a;}
inline int sub(int a,int b){a-=b;if(a<0) a += mod; return a;}
inline int mul(int a, int b){ return a*1ll*b%mod;}
inline int power(int x, ll y){
  int res = 1;
  while(y){
    if(y&1) res = mul(res , x);
    x = mul(x,x);
    y >>= 1;
  }
  return res;
}

pii sovle(ll n){
  int a = 0 , b = 0;
  while(n%2 == 0){
    ++a;
    n /= 2;
  }
  while(n%5 == 0){
    ++b;
    n /= 5;
  }
  return mp(a,b);
}
const int N = 18;
ll pwr[N];

int main(){
  fio; cout<<fixed<<setprecision(25);
  pwr[0] = 1;
  for(int i = 1;i < N ; ++i) pwr[i] = pwr[i-1]*10;
  int n; cin >> n;
  map<pii,ll> m;
  string s;
  for(int i =1 ;i <= n ; ++i){
    cin >> s;
    int id = -1;
    int j = 0;
    for(auto it :s){
      if(it == '.'){
        id = j;
        break;
      }
      ++j;
    }
    ll a = 1 , b = 1;
    if(id == -1){
      a = stoll(s);
    }
    else{
      int len = s.size()-j-1;
      b = pwr[len];
      s.erase(s.begin()+id);
      a = stoll(s);
    }
    ll gd = __gcd(a,b);
    a /= gd;
    b /= gd;
    pll p1 = sovle(a);
    pll p2 = sovle(b);
    p1.F -= p2.F;
    p1.S -= p2.S;
    m[p1]++;
  }
  ll ans = 0;

  for(auto &it : m){
    for(auto &it2 : m){
      if(it.F.F+it2.F.F >= 0 && it.F.S+it2.F.S >= 0){
        ans += it.S*it2.S;
        if(it == it2)
          ans -= it.S;
      }
    }
  }
  cout << ans/2 << endl;

  return 0;
}


// AtCoder Beginner Contest 167 - Problem F: Bracketing Sequencing (https://atcoder.jp/contests/abc167/tasks/abc167_f)
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ii = pair<ll, ll>;

string solve(int N, const vector<string>& xs)
{
    vector<int> cs;
    vector<ii> ds, es;

    int open = 0, close = 0;

    for (int i = 0; i < N; ++i)
    {
        int a = 0, b = 0;

        for (auto c : xs[i])
        {
            open += (c == '(' ? 1 : 0);
            close += (c == ')' ? 1 : 0);

            b += (c == '(' ? 1 : -1);

            if (b < 0)
            {
                a--;
                b = 0;
            }
        }

        if (b + a >= 0)
            ds.push_back(ii(-a, i));
        else
            es.push_back(ii(b, i));
    }

    if (open != close)
        return "No";

    sort(ds.begin(), ds.end());
    sort(es.begin(), es.end(), greater<ii>());

    int s = 0;

    for (auto p : ds)
    {
        auto i = p.second;

        for (auto c : xs[i])
        {
            s += (c == '(' ? 1 : -1);

            if (s < 0)
                return "No";
        }
    }

    for (auto p : es)
    {
        auto i = p.second;

        for (auto c : xs[i])
        {
            s += (c == '(' ? 1 : -1);

            if (s < 0)
                return "No";
        }
    }

    return "Yes";
}

int main()
{
    ios::sync_with_stdio(false);

    int N;
    cin >> N;

    vector<string> xs(N);

    for (int i = 0; i < N; ++i)
        cin >> xs[i];

    auto ans = solve(N, xs);

    cout << ans << '\n';

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vii;
typedef vector<ll> vll;
typedef pair<ll,ll> pii;

#define pb push_back
#define odd(x) ((x)&1)
#define even(x) (!odd(x))
#define ff it->first
#define ss it->second
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(auto i=0;i<n;++i)
#define LOOP_IT(it,s) for(auto it=(s).begin();it!=(s).end();++it)
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

#ifdef LOCAL
#define cerr cout
#else
#endif

#define TRACE

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

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

vector<pii> v;

pii fxn(string s)
{
    ll n = s.size();
    ll cnt=0;
    ll x=0,y=0;

    rep(i,n)
    {
        if(s[i]=='(')
            ++cnt;
        else
            --cnt;
        if(cnt<0)
            {++x;cnt=0;}
    }
    y = cnt;

    pii p = {x,y};
    return p;
}

bool cmp1(pii a,pii b)
{
    if(a.first!=b.first)
        return (a.first<b.first);
    return (a.second>b.second);
}
bool cmp2(pii a,pii b)
{
    if(a.second!=b.second)
        return (a.second>b.second);
    return (a.first<b.first);
}

bool chk(vector<pii> &v)
{
    ll sum=0;
    ll n = v.size();
    for(auto p:v)
    {
        sum-=p.first;
        if(sum<0)
        {
            return false;
        }
        sum+=p.second;
    }
    if(sum)
    {
        return false;
    }
    for(ll i=n-1;i>=0;--i)
    {
        pii p = v[i];
        sum+=p.first;
        sum-=p.second;
        if(sum<0)
        {
            return false;
        }
    }
    if(sum)
    {
        return false;
    }
    return true;
}

bool cmp3(pii a,pii b)
{
    ll x = a.second-a.first;
    ll y = b.second-b.first;
    return (x>y);
}

int main(int argv, char* argc[])
{
    FASTIO

    ll n;
    cin>>n;
    string s[n];
    v.resize(n);

    rep(i,n)
    {
        cin>>s[i];
        v[i] = fxn(s[i]);
    }

    sort(all(v),cmp3);
    ll ind =-1;

    for(ll i=0;i<n;++i)
    {
        if(v[i].second-v[i].first<=0)
        {
            ind = i;break;
        }
    }

    if(ind==-1)
        goto label;

    sort(v.begin(),v.begin()+ind,cmp1);
    sort(v.begin()+ind,v.end(),cmp2);
    if(chk(v))
    {
        cout<<"Yes";
        return 0;
    }
    label:
    cout<<"No";

    return 0;
}


///f. fizzbuzz sequence
#include <stdio.h>
#include <math.h>

int main()
{
    long long int n;
    scanf("%lld",&n);
    long long int d3,d5,d15;
    d3=n/3; d5=n/5; d15=n/15;

    long long sum = (n*(n+1)-3*d3*(d3+1)-5*d5*(d5+1)+15*d15*(d15+1))/2;
    printf("%lld",sum);
    return 0;
}

#include <iostream>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
#define MOD 1000000007;

void solve(){
  int n; cin >> n;
  long long ans = 1;
  vector<int> pn;
  map<int, int> mp;
  for(int i = 2; i <= n; ++i){
    int cnt = 0;
    for(int j = 1; j <= i; ++j){
      if(i % j == 0)cnt++;
    }
    if(cnt == 2) pn.push_back(i);
  }
  for(int i = 2; i <= n; ++i){
    int tmp = i;
    while(tmp !=1){
      for(auto p : pn){
        if(tmp%p == 0) {
          mp[p]++;
          tmp/=p;
          if(tmp == 1)break;
        }
      }
    }
  }
  for(auto m: mp){
    ans *= (m.second+1);
    ans %= MOD;
  }
  cout << ans << endl;
}

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


#include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;
const LL MOD = 1e9 + 7;
const int MAXV = 1e5 + 5;
double solve(int a, int b, int c, auto &dp, int n) {
    if (dp[a][b][c] != -1) return dp[a][b][c];
    double sum = 0;
    if (a - 1 >= 0)
        sum += solve(a - 1, b, c, dp, n) / n * a;
    if (b - 1 >= 0)
        sum += solve(a + 1, b - 1, c, dp, n) / n * b;
    if (c - 1 >= 0)
        sum += solve(a, b + 1, c - 1, dp, n) / n * c;
    sum++;
    sum *= n, sum /= a + b + c;
    return dp[a][b][c] = sum;
}
void marmot0814() {
    int n; cin >> n;
    vector<LL> cnt(3, 0);
    for (int i = 0 ; i < n ; i++) {
        int v; cin >> v; v--;
        cnt[v]++;
    }
    vector<vector<vector<double>>> dp(n + 1, vector<vector<double>>(n + 1, vector<double>(n + 1, -1)));
    dp[0][0][0] = 0;
    cout << fixed << setprecision(20) << solve(cnt[0], cnt[1], cnt[2], dp, n) << '\n';
}
int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);
    int t = 1, kase = 0; // cin >> t;
    while (t--) {
        // cout << "Case #" << ++kase << ":";
        marmot0814();
    }
}

/* Bismillahir Rahmanir Rahim */
#include<bits/stdc++.h>
#include<vector>
#include<cmath>
#include<string>
#include<stdlib.h>
#define   mod          1000000007
#define   lp(i,a,b)    for(ll i=a;i<=b;i++)
#define   ll           long long int
#define   ull          unsigned long long int
#define   tst          int t;cin>>t;while(t--)
#define   pb           push_back
#define   vi(v)        vector<int>v;
#define   vl(v)        vector<ll>v;
#define   vs           vector<string>v
#define   rslt(x)      cout<<x<<endl;
#define   mp(x,y)      make_pair(x,y)
#define   yes          rslt("YES");
#define   no           cout<<"NO"<<endl;
#define   srt(v)       sort(v.begin(),v.end())
#define   rvs(v)       reverse(v.begin(),v.end());
#define   AR           ios::sync_with_stdio(false);cin.tie(0);
#define   gcd(a,b)     __gcd(a,b)
#define   lcm(a,b)     (a/gcd(a,b))*b
#define   max          1000007
#define   str          int s[200000];
#define   coutv(v)     for(auto it:v)cout<<it<<' ';cout<<endl;
#define   cinv(v)      for(auto &it:v)cin>>it;
using namespace std;
int main()
{
    ll n,x=0;
    str
    cin>>n;
    ll cnt=0;
    lp(i,0,n-1)
    cin>>s[i];
    sort(s,s+n);
    for(int i=0; i<n-2; i++)
    {
        for(int j=i+1; j<n-1; j++)
        {
            for(int k=j+1; k<n; k++)
            {
                x=0;
                if(s[i]!=s[j] && s[j]!=s[k])
                {
                    if(s[i]+s[j]>s[k])
                        x++;
                    if(s[i]+s[k]>s[j])
                        x++;
                    if(s[j]+s[k]>s[i])
                        x++;
                    if(x==3)
                        cnt++;
                }
            }
        }
    }
    cout<<cnt<<endl;

    return 0;

}


#include <bits/stdc++.h>
#define rep(i,n) for(long long i=0; i<n; i++)
#define Rep(i,n) for(long long i=1; i<n; i++)
#define ll long long
#include <math.h>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <queue>
#include <set>
#include <vector>

using namespace std;
#define PI acos(-1)

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

  cout<<2*N*PI<<endl;
  return 0;
}

#include <iostream>
using namespace std;

int main()
{
  int x, coin500, coin5;
  cin >> x;
  coin500 = x / 500;
  x -= coin500 * 500;
  coin5 = x / 5;
  cout << coin500 * 1000 + coin5 * 5 << endl;
  return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;
const int Max_L(50);
typedef long long int LL;

int L, len, D[Max_L], N[Max_L], X[Max_L];
char input[Max_L];
LL Ans;

int work(int p, int x)
{
	int Ret(0);
	for (int c = (p == len - 1 ? 1 : 0);c <= 9;++c)
		if (0 <= c - x && c - x <= 9)
			++Ret;
	return Ret;
}

bool check()
{
	for (int i = len - 1, j;i >= 0;--i)
	{
		X[j = i] = N[i];
		while (X[j] < 0)
		{
			if (j == len - 1)
				return false;
			X[j] += 10, --X[++j];
		}
	}
	for (int i = 0;i <= len - 1;++i)
		if (X[i] != D[i])
			return false;
	return true;
}

void dfs(int p, int a, int b, int v, LL Ret = 1LL)
{
	if (!Ret)
		return;
	if (a <= b)
	{
		if (a == b)
			Ret *= work(a, 0);
		if (check())
			Ans += Ret;
		return;
	}
	int x = (D[p] + v) % 10;
	if (x == 0)
		if (D[p] + v == 0)
			N[p] = 0, N[len - 1 - p] = 0, dfs(p + 1, a - 1, b + 1, 0, Ret * work(a, 0));
		else
			N[p] = 0, N[len - 1 - p] = 0, dfs(p + 1, a - 1, b + 1, 1, Ret * work(a, 0));
	else
	{
		N[p] = x, N[len - 1 - p] = -x, dfs(p + 1, a - 1, b + 1, 0, Ret * work(a, x));
		N[p] = x - 10, N[len - 1 - p] = 10 - x, dfs(p + 1, a - 1, b + 1, 1, Ret * work(a, x - 10));
	}
}

int main()
{
	scanf("%s", input), L = strlen(input);
	for (int i = 0;i <= L - 1;++i)
		D[i] = input[L - 1 - i] - '0';
	for (len = L;len <= 19;++len)
		memset(N, 0, sizeof(N)), dfs(0, len - 1, 0, 0);
	printf("%lld", Ans);
	return 0;
}

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <locale>
#include <iostream>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()

using namespace std;

using ll = long long;
using ld = long double;

template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template <typename T> int len(const T &x) { return x.size(); }

template<typename T>
vector<T> table(int n, T v) { return vector<T>(n, v); }

template <class... Args>
auto table(int n, Args... args) {
  auto val = table(args...);
  return vector<decltype(val)>(n, move(val));
}

struct yes_no : numpunct<char> {
  string_type do_truename()  const { return "YES"; }
  string_type do_falsename() const { return "NO"; }
};

ll tens[32];

ll dp(const int digit, const ll D, bool zero) {
  if (digit == 1) return (D == 0 ? 10 : 0);
  if (digit == 0) return (D == 0 ? 1 : 0);
  if (abs(D) > tens[digit]) return 0;
  ll res = 0;
  for (int diff = -9; diff <= 9; ++diff) {
    int count = 10 - abs(diff) - (zero ? 1 : 0);
    ll nD = D - diff * (tens[digit - 1] - 1);
    if (nD % 10 == 0) res += dp(digit - 2, nD / 10, false) * count;
  }
  return res;
}

void solve(const ll D) {
  tens[0] = 1;
  REP(i,18) tens[i + 1] = tens[i] * 10;
  ll res = 0;
  for (int digit = 1; digit <= 18; ++digit) {
    res += dp(digit, D, true);
  }
  cout << res << endl;
}

int main() {
  locale loc(locale(), new yes_no);
  cout << boolalpha << setprecision(12) << fixed;
  cout.imbue(loc);
	ll D;
	scanf("%lld", &D);
	solve(D);
	return 0;
}


#include<iostream>
#include<iomanip>
#include<queue>
#include<string>
#include<stack>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<cassert>
#include<ctime>
#include<algorithm>
#include<utility>
#include<map>
#include<set>
#include<vector>
#include<functional>

using namespace std;

#ifdef DEBUG
#define dprintf      printf
#define dout(x)      cout<<#x" = "<<(x)<<endl
#define darray(x,n)    {int i;rep(i,n)cout<<#x"["<<i<<"] = "<<*((x)+i)<<endl;}
#define dloop(i,s,g) for((i)=(s);(i)<(g);(i)++)
#define drep(i,n)    for((i)=0;(i)<(n);(i)++)
#define dstop()      scanf("%*c")
#else
#define dprintf      (1)?0:printf
#define dout(x)
#define darray(x,n)
#define dloop(i,s,g) if(1){}else
#define drep(i,n)    if(1){}else
#define dstop()      if(1){}else
#endif

#define F    first
#define S    second
#define pb   push_back
#define mp   make_pair

#define loop(i,s,g) for((i)=(s);(i)<(g);(i)++)
#define rep(i,n)    for((i)=0;(i)<(n);(i)++)
#define all(x)      (x.begin(),x.end())
#define in(T,...) T __VA_ARGS__; impl(__VA_ARGS__);
#define array(T,id,n) T id[n]; rep(i,n)cin>>id[i];

//#define int long long;
#ifndef int
#define INF  (0x7fffffff)
#else
#define LINF (0x7fffffffffffffff)
#endif

typedef  long long           ll;
typedef  unsigned            ui;
typedef  unsigned long long  ull;
typedef  pair<int,int>       i_i;
typedef  pair<ll,int>        ll_i;
typedef  pair<ll,ll>         ll_ll;
typedef  pair<double,int>    d_i;
typedef  pair<double,double> d_d;

void impl(){};
template <typename T,typename... TS >
void impl(T &head,TS &... tail)
{
  cin>>head;
  impl(tail ...);
}
#define UNION_FIND_MAX_N (112345)
int union_find_par[UNION_FIND_MAX_N];
int union_find_rank[UNION_FIND_MAX_N];

void init(int n)
{
  int i;
  for(i=0;i<n;i++)
    {
      union_find_par[i]=i;
      union_find_rank[i]=0;
    }
}

int find(int x)
{
  if(union_find_par[x]==x)
    return x;
  else
    return union_find_par[x]=find(union_find_par[x]);
}

void unite(int x,int y)
{
  x=find(x);
  y=find(y);
  if(x==y)
    return;
  if(union_find_rank[x]<union_find_rank[y])
    union_find_par[x]=y;
  else
    union_find_par[y]=x;
  if(union_find_rank[x]==union_find_rank[y])
    union_find_rank[x]++;
}

int nsame(int x,int y)
{
  return find(x)!=find(y);
}

typedef struct edge
{
  int u;
  int v;
  int cost;
  bool operator>(const edge&right)const
  {
    return cost>right.cost;
  }
  bool operator<(const edge&right)const
  {
    return cost<right.cost;
  }
}Edge;

signed main(void)
{
  int n;
  Edge edge[112345]={};
  int i,j,k=0;
  int sum=0;
  cin>>n;
  init(n);
  rep(i,n)rep(j,n)
    {
      cin>>edge[k].cost;
      edge[k].u=i;
      edge[k].v=j;
      k++;
    }
  sort(edge,edge+k);
  rep(i,k)
    if(edge[i].cost!=-1)
      if(nsame(edge[i].u,edge[i].v))
	unite(edge[i].u,edge[i].v),sum+=edge[i].cost;

  cout<<sum<<endl;
  return 0;
}

#include<bits/stdc++.h>
#include<ctype.h>
# define pb push_back
#define fst first
#define sec second
#define For(i,a,b) for(int i=a;i<b;i++)
#define ll long long int
#define ull unsigned long long int
#define mod 1000000007
#define fo(i,n) for(ll i=0;i<n;i++)
#define endl "\n"
#define rev(i,n) for(ll i=n-1;i>=0;i--)
#define fo1(i,n) for(ll i=1;i<=n;i++)
#define boolsize 1000001
#define pi pair<ll,ll>
#define vi vector<ll>
#define vii vector<pi>
using namespace std;
template<typename T>
void showvector(vector <T> v)
{
    for(T x:v)
        cout<<x<<" ";
    cout<<endl;

}
template<typename T>
void showvector1(vector <T> v)
{
    ll n=v.size();
    fo1(i,n-1)
        cout<<v[i]<<endl;

}
template<typename T>
void showset(set <T> s)
{
    for(T x: s)
        cout<<x<<" ";
    cout<<endl;
}
template<class T>
void showvectorpair(vector<T> v)
{
    for(auto it=v.begin();it!=v.end();it++)
        cout<<it->first<<" "<<it->second<<endl;
    cout<<endl;
}
template<typename T,typename P>
void showmap(map <T,P> m)
{
    for(auto it=m.begin();it!=m.end();it++)
        cout<<it->first<<" "<<it->second<<endl;
    cout<<endl;
}
template<typename T>
bool comp(T a,T b)
{
    return (a>b);
}
template<class T>
bool comppair(T a,T b)
{
    if(a.first==b.first)
        return(a.second>b.second);
    return (a.first>b.first);
}
bool sameparity(ll a,ll b)
{
    return (a%2==b%2);
}
bool difparity(ll a,ll b)
{
    return !(a%2==b%2);
}
bool isprime(ll x)
{   if(x<=1)
     return false;
    for(ll i=2;i<=sqrt(x);i++)
    {
        if(x%i==0)
            return false;
    }
    return true;
}
bool iseven(ll x)
{
    return !(x%2);
}
bool isodd(ll x)
{
    return (x%2);
}
//vector <bool> prime(boolsize,1);
//void seive()
//{
//    ll n=boolsize;
//    prime[0]=prime[1]=0;
//    for(ll i=2;i<=sqrt(boolsize);i++)
//    {
//        if(prime[i]==1)
//        {
//            for(ll j=i*i;j<=n;j+=i)
//            {
//                prime[j]=0;
//            }
//        }
//    }
//}

/// check for test case before submitting
void vfun()
{
    ll n,k;
    cin>>n>>k;
    vi v(n);
    fo(i,n)
    cin>>v[i];
    sort(v.begin(),v.end(),comp<ll>);
    ll sum=0;
    fo(i,k)
    sum+=v[i];
    cout<<sum<<endl;

}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(0); ///cant use scanf, printf
    cin.tie(0);cout.tie(0); /// no longer auto flush cout before each cin, remove for interactive
    //cout << fixed << setprecision(11); /// no scientific output
    ll test=1;
    //cin>>test;
    while(test--)
    {

        //fun();
        vfun();
//         if(vfun())
//            cout<<"YES\n";
//         else
//            cout<<"NO\n";
    }
}
///before sub
/// check for value of zero and single input in array
///loop vars,1LL in mult, equal, one, bounds, int v ll, endl, finish taking inputs
/// check whether test cases are given or not


/**
 * @copyright (c) 2020 Daisuke Hashimoto
 */

#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using Pair = pair<int64_t, int64_t>;

// std::cout << std::setprecision(20) << 1.1 << endl;

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

  int64_t N;
  string s, t;
  cin >> N >> s >> t;
  int64_t overwrap = 0;
  for (int64_t ov = 1; ov <= N; ++ov) {
    if (s.substr(N - ov, ov) == t.substr(0, ov)) {
      overwrap = ov;
    }
  }
  // const int64_t L = static_cast<int64_t>(T.length());
  cout << (N * 2 - overwrap) << endl;
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
const int N=2e2+5,mod=1e9+7;
ll n,m,k,dp[N][N],num[N][N];
int main(){
	cin>>n>>m>>k;
	for(int s=0;s<(1<<(m-1));s++){
		bool ok=true;
		for(int j=0;j<m-1;j++){
			int b1=(s>>j)&1;
			int b2=(s>>(j+1))&1;
			if(b1==b2&&b1)	ok=false;
		}
		if(!ok)	continue;
		for(int j=0;j<m;){
			if((s>>j)&1){
				num[j][j+1]++,num[j+1][j]++;
				j+=2;
			}
			else{
				num[j][j]++;
				j++;
			}
		}
	}
	dp[0][0]=1;
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
			for(int p=0;p<m;p++)	dp[i+1][p]=(dp[i+1][p]+(dp[i][j]*num[j][p])%mod)%mod;
	cout<<dp[n][k-1]<<'\n';
	return 0;
}


#include <bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
#define int long long
using namespace std;
int dp[111][111],n,L[111],R[111];

int dfs(int l,int r){
	if(dp[l][r]!=-1)return dp[l][r];
	if(l==r)return dp[l][r]=0;
	int res=1e17;
	for(int i=l;i<r;i++){
		res=min(res,dfs(l,i)+dfs(i+1,r)+L[l]*R[i]*R[r]);
	}
	return dp[l][r]=res;
}

signed main(){
	memset(dp,-1,sizeof(dp));
	cin>>n;
	r(i,n)cin>>L[i]>>R[i];
	dfs(0,n-1);
	cout<<dp[0][n-1]<<endl;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U> using Pa = pair<T, U>;
template <class T> using vec = vector<T>;
template <class T> using vvec = vector<vec<T>>;

int main(){
    int X,Y;
    cin >> X >> Y;
    int ans = 2e9+1;
    for(int i=0;i<2;i++) for(int j=0;j<2;j++){
        int x = (i? -X:X),y = (j? -Y:Y);
        if(x<=y) ans = min(ans,i+j+y-x);
    }
    cout << ans << "\n";
}

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

using namespace std;
 int main(){

  long long  x,y;
  cin>>x>>y;

  if(x*y < 0) cout<<abs(abs(x) - abs(y))+1<<endl;
  else if(x*y == 0){

   if(x<y) cout<<y-x<<endl;
   else cout<<x-y+1<<endl;
  }
  else {
     if(x<y) cout<<y-x<<endl;
     else
        cout<<x-y+2<<endl;

  }

 return 0;
 }


#include <iostream>

using namespace std;

void solve()
{
	int l[10];
	while(cin >> l[0])
	{
		for(int i = 1; i <= 9; ++i)
		{
			scanf(",%d", &l[i]);
		}
		int v[2];
		scanf(",%d,%d", &v[0], &v[1]);
		int sum = 0;
		for(int i = 0; i < 10; ++i)
		{
			sum += l[i];
		}
		double time = (double)sum / (v[0] + v[1]);
		double dist = time * (double)v[0];
		int pos = 0;
		int d = 0;
		while(true)
		{
			d += l[pos];
			if(d >= dist)
			{
				cout << pos + 1 << endl;
				break;
			}
			++pos;
		}
	}
}

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

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

int main() {
    int n,k;
    cin >> n >> k;
    vector<int> l(n);

    for (int i = 0; i < n; i++)
    {
        cin >> l[i];
    }
    sort(l.begin(),l.end());
    reverse(l.begin(),l.end());
    int x = 0;
    for (int i = 0; i < k; i++)
    {
        x += l.at(i);
    }
    cout << x << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
#define all(x) x.begin(),x.end()
#define rep(i,j,n) for (int i = j; i < (int)(n); i++)
#define _GLIBCXX_DEBUG
#define MOD 1000000007
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; }
//name[i][j]-> vvl name(i,vl(j))
//map<int,int>mp
//余りを切り上げる =>  (a + b - 1) / b

signed main(){
	int s; cin>>s;
	cout<<s/3;

	return 0;
}

// A - Rated for Me
#include <bits/stdc++.h>
using namespace std;

int main(){
	int r; cin>>r;
	string ans = "ARC";
	if(r < 1200) ans = "ABC";
	if(2800 <= r) ans = "AGC";
	cout<< ans <<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define per1(i,n) for(int i=n;i>0;i--)
#define all(v) v.begin(), v.end()
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<ll> vec;
typedef vector<vec> mat;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,m,d;
    cin>>n>>m>>d;
    cout<<setprecision(10)<<(double)(n-d)*(m-1)/n/n*(2-(!d));
}

#include<stdio.h>
#include<math.h>

int main(){
	double a,b,c,d;
	scanf("%lf %lf %lf %lf",&a,&b,&c,&d);
	printf("%.8lf\n",sqrt(pow(c-a,2.0)+pow((d-b),2.0)));
}


#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define REPS(I, a, b) for (int i = (a); i < (b); ++i)
using namespace std;
using ll = long long;

int main() {
  string s;
  cin >> s;

  bool ok = false;
  REP(i,3){
    if(s[i] == '7') ok = true;
  }

  if(ok) cout << "Yes" << endl;
  else cout << "No" << endl;

}

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

int main() {
  string s;
  cin >> s;
  rep(i, s.size()-8) cout << s[i];
  cout << endl;
  return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <iomanip>

using namespace std;
using ll = long long;
using vi = vector<int>;
using vl = vector<long long>;
template<class T>using vv = vector<vector<T>>;
using vvi = vv<int>;
using vvl = vv<long long>;

#define in(v) v; cin >> v;
void ins() {}
template<class T,class... Rest>void ins(T& v,Rest&... rest){cin>>v;ins(rest...);}

#define _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) for(int i=0,_i=(n);i<_i;++i)
#define repi(i,a,b) for(int i=(a),_i=(b);i<_i;++i)
#define rep(...) _overload3(__VA_ARGS__,repi,_rep,)(__VA_ARGS__)
#define all(f,c,...) (([&](decltype((c)) cccc) { return (f)(begin(cccc), end(cccc), ## __VA_ARGS__); })(c))

// debug
template<class T>ostream& operator<<(ostream& os,const vector<T>& vec){os<<"{";for(size_t i=0;i<vec.size();++i)os<<(i?", ":"")<<vec[i];os<<"}";return os;}
ostream& operator<<(ostream& os,const vector<char>&v){for(size_t i=0;i<v.size();++i)os<<v[i];return os;}
template<class T1,class T2>ostream& operator<<(ostream& os,const pair<T1,T2>& rhs){os<<"("<<rhs.first<<", "<<rhs.second<<")";return os;}

#ifdef LOCAL
void debug() {cerr << "\n";}
template<class First> void debug(const First& first) {cerr<<first<<"\n";}
template<class First, class... Rest> void debug(const First& first, const Rest&... rest) {cerr<<first<<",";debug(rest...);}
void debug2() {cerr << "\n";}
template<class First> void debug2(const First& first) {cerr<<first<<" ";}
template<class First, class... Rest> void debug2(const First& first, const Rest&... rest) {cerr<<first<<" ";debug2(rest...);}
#else
#define debug(...) 42
#define debug2(...) 42
#endif

int N;
vv<int> A;
ll dp[1<<16][16];
const ll INF = 1e15;
ll dfs(int used, int i) {
  if (i == N)
    return 0;

  if (dp[used][i] != INF)
    return dp[used][i];

  if (used & (1 << i))
    return dfs(used, i+1);

  ll ans = 0;

  vi notUsed;
  rep(j, N)
    if (!(used & (1 << j))) {
      if (j < i)
        return -INF;
      notUsed.push_back(j);
    }

  rep(bit, 1 << (notUsed.size())) {
    ll tmp = 0;
    int used2 = 0;
    rep(j, notUsed.size()) {
      if (bit & (1 << j)) {
        used2 |= 1 << notUsed[j];
        rep(k, j+1, notUsed.size()) {
          if (bit & (1 << k))
            tmp += A[notUsed[j]][notUsed[k]];
        }
      }
    }
    ans = max(ans, tmp + dfs(used | used2, i+1));
  }
  return dp[used][i] = ans;
}
int main() {
  in(N);
  A.resize(N, vector<int>(N, 0));

  rep(i, 1<<16) rep(j, 16) dp[i][j] = INF;
  rep(i, N) rep(j, N) {
    cin >> A[i][j];
  }
  cout << dfs(0, 0) << endl;

  return 0;
}

#include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;
const LL MOD = 1e9 + 7;
LL cal(int S, auto &arr, auto &sum) {
    if (~sum[S]) return sum[S];
    sum[S] = 0; int n = arr.size();
    for (int i = 0 ; i < n ; i++)
        for (int j = i + 1 ; j < n ; j++)
            if (((S >> i) & 1) & ((S >> j) & 1))
                sum[S] += arr[i][j];
    return sum[S];
}
LL solve(int S, auto &dp, auto &arr, auto &sum) {
    if (~dp[S]) return dp[S];
    dp[S] = 0;
    for (int s = S ; s ; s = (s - 1) & S)
        dp[S] = max(dp[S], solve(S ^ s, dp, arr, sum) + cal(s, arr, sum));
    return dp[S];
}
void marmot0814() {
    int n; cin >> n;
    vector<vector<LL>> arr(n, vector<LL>(n));
    for (auto &vv : arr)
        for (auto &v : vv)
            cin >> v;
    vector<LL> dp(1 << n, -1); dp[0] = 0;
    vector<LL> sum(1 << n, -1);
    cout << solve((1 << n) - 1, dp, arr, sum) << '\n';
}
int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);
    int t = 1, kase = 0; // cin >> t;
    while (t--) {
        // cout << "Case #" << ++kase << ":";
        marmot0814();
    }
}


#include <bits/stdc++.h>
#define rep(i, a, n) for (int i = a; i < n; i++)
#define repr(i, a, n) for (int i = n - 1; i >= a; i--)
using namespace std;
using ll = long long;
using P = pair<int, int>;
template <typename T> void chmin(T &a, T b) { a = min(a, b); }
template <typename T> void chmax(T &a, T b) { a = max(a, b); }

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

  int n;
  cin >> n;
  vector<int> l(n * 2);
  rep(i, 0, n * 2) cin >> l[i];
  sort(l.begin(), l.end());

  int ans = 0;
  rep(i, 1, n * 2) {
    ans += min(l[i], l[i - 1]);
    i++;
  }

  cout << ans << endl;
}

#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <fstream>
#include <bitset>
#include <queue>
#include <stack>
#include <deque>
#include <complex>
#include <iomanip>
#include <stdio.h>
#include <string.h>
#include <random>
#include <functional>

using std::cin;
using std::cout;
using std::cerr;
using std::endl;

using std::map;
using std::set;
using std::bitset;
using std::vector;
using std::string;
using std::multimap;
using std::multiset;
using std::deque;
using std::queue;
using std::stack;
using std::pair;
using std::iterator;

using std::sort;
using std::stable_sort;
using std::reverse;
using std::max_element;
using std::min_element;
using std::unique;
using std::ios_base;
using std::swap;
using std::fill;

using std::setprecision;
using std::fixed;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef string S;

ll min(ll a, ll b) {return a < b ? a : b;}
ll min(int a, ll b) {return a < b ? a : b;}
ll min(ll a, int b) {return a < b ? a : b;}
ll min(int a, int b) {return a < b ? a : b;}

ll max(ll a, ll b) {return a > b ? a : b;}
ll max(int a, ll b) {return a > b ? a : b;}
ll max(ll a, int b) {return a > b ? a : b;}
ll max(int a, int b) {return a > b ? a : b;}

namespace MySpace{

};

#define F(i, n) for (int (i) = 0; (i) != (n); (i)++)
#define fi first
#define se second
#define re return
#define all(x) (x).begin(), (x).end()

const int MOD = 1e9 + 7;
ll n, m, k;

vector<int> mul(vector<int> a, vector<int> b)
{
    vector<int> c(a.size());
    for (int i = 0; i < a.size(); i++)
    {
        c[i] = a[b[i]];
    }
    return c;
}

vector<double> mul(vector<double> a, vector<int> b)
{
    vector<double> c(a.size());
    for (int i = 0; i < a.size(); i++)
    {
        c[i] = a[b[i]];
    }
    return c;
}

vector<int> inq(vector<int> perm, ll k)
{
    if (k == 0)
    {
        vector<int> c;
        for (int i = 0; i < perm.size(); i++) c.push_back(i);
        return c;
    }
    vector<int> l = inq(perm, k / 2);
    if (k % 2) return mul(mul(l, l), perm);
    return mul(l, l);
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    vector<double> x(n);
    for (int i = 0; i < n; i++)
    {
        cin >> x[i];
    }
    cin >> m >> k;
    vector<int> perm(n - 1);
    iota(all(perm), 0);
    for (int i = 0; i < m; i++)
    {
        int x;
        cin >> x;
        x--;
        swap(perm[x - 1], perm[x]);
    }
    vector<int> c = inq(perm, k);
    vector<int> y(n - 1);
    for (int i = 0; i + 1 < n; i++)
    {
        y[i] = x[i + 1] - x[i];
    }
    y = mul(y, c);
    double s = x[0];
    for (int i = 0; i < n; i++)
    {
        printf("%.9f\n", s);
        if (i != n - 1)
            s += y[i];
    }
}


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

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

int main()
{
    int n; cin >> n;
    vector<int> a(n), groups;
    rep(i, n) cin >> a[i];

    groups.push_back(a[0]);
    rep(i, n-1){
        int ng = -1, ok = groups.size();
        while(ok - ng > 1){
            int mid = (ng + ok) / 2;
            if(groups[mid] < a[i + 1])
                ok = mid;
            else
                ng = mid;
        }
        if(ok == groups.size())
            groups.push_back(a[i + 1]);
        else
            groups[ok] = a[i + 1];
    }

    cout << groups.size() << endl;
    return 0;
}

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

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    cin >> N;
    vector<int> A(N);
    for(int i=0; i<N; i++) cin >> A[i];

    multiset<int> ms;
    for(auto a : A)
    {
        if(ms.empty() || *ms.begin() >= a) ms.insert(a);
        else
        {
            auto itr = ms.lower_bound(a);
            if(itr == ms.end() || *itr >= a) itr--;
            ms.erase(itr);
            ms.insert(a);
        }
    }
    cout << ms.size() << endl;

    return 0;
}


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

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------

string S;
int N,K;

const ll mo=998244353;

ll from[303][306];
ll to[303][306];

void solve() {
	int i,j,k,l,r,x,y; string s;

	cin>>S>>K;
	vector<int> V;
	V.push_back(0);

	int sum=0;
	FORR(c,S) {
		if(c=='1') V.back()++, sum++;
		else V.push_back(0);
	}
	K=min(K,sum);
	N=V.size();

	from[K][0]=1;
	FOR(y,V.size()) {
		int v=V[y];
		ZERO(to);
		for(j=K;j>=0;j--) {
			for(i=0;i<=sum;i++) if(from[j][i]) {
				for(int tar=0;tar<=min(v+j,sum);tar++) {
					if(y==V.size()-1 && tar>v) break;
					if(tar<=v) {
						if(i+(tar-v)>=0) (to[j][i+(tar-v)]+=from[j][i])%=mo;
					}
					else {
						(to[j-(tar-v)][i+(tar-v)]+=from[j][i])%=mo;
					}
				}
			}
		}
		swap(from,to);
	}

	ll ret=0;
	FOR(i,K+1) ret+=from[i][0];
	cout<<ret%mo<<endl;

}

int main(int argc,char** argv){
	string s;int i;
	if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
	FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
	cout.tie(0); solve(); return 0;
}

#include <cstdio>
#include <algorithm>
#include <iostream>
// 18:45 -
using namespace std;

int main(void)
{
    while(1){
        int n, p;
        scanf("%d %d", &n, &p);
        if(n == 0 & p == 0)
            break;
        int mine[n];
        for(int i = 0; i < n; i++) mine[i] = 0;
        int all = 0;
        int count = 0;
        while(1){
            all = 0;
            if(p > 0){
                p--;
                mine[count % n]++;
                for(int i = 0; i < n; i++) all += mine[i];
                all -= mine[count % n];
                if(all == 0 && p == 0){
                    break;
                }
            } else if(p == 0){
                p += mine[count % n];
                mine[count % n] = 0;
            }
            count++;
        }
        printf("%d\n", count % n);
    }

    return 0;
}


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

int main(){
    int n; cin>>n;
    string s; cin >> s;
    string t; cin >> t;

    int cnt=0;
    bool flg = false;
    for(int i=0; i<s.length(); i++){
        string s_sub = s.substr(i, s.length()-i);
        for(int j=0; j<t.length(); j++){
            string t_sub = t.substr(0, t.length()-j);
                if(s_sub==t_sub){
                    cnt = s_sub.length();  flg = true;
                    break;
                }
            }

        if(flg) break;
    }
    string res = s + t.substr(cnt, t.length()-cnt);
    int ans = res.length();
    cout << ans << endl;
    return 0;

}

#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <tuple>
#include <iomanip>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vec;
typedef vector<vec> mat;
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define revrep(i, n) for(ll i = (n)-1; i >= 0; i--)
#define pb push_back
#define f first
#define s second
ll max(ll a, ll b){return (a > b) ? a : b;}
ll min(ll a, ll b){return (a < b) ? a : b;}
ll max3(ll a, ll b, ll c){return max(a, max(b, c));};
ll min3(ll a, ll b, ll c){return min(a, min(b, c));};
ll max4(ll a, ll b, ll c, ll d){return max(max(a, b), min(c, d));};
ll min4(ll a, ll b, ll c, ll d){return min(min(a, b), min(c, d));};
ll max5(ll a, ll b, ll c, ll d, ll e){return max(max(a, b), max3(c, d, e));};
ll min5(ll a, ll b, ll c, ll d, ll e){return min(min(a, b), min3(c, d, e));};

const ll INFL = 1LL << 60;//10^18 = 2^60
const int INF = 1 << 30;//10^9
ll MOD = 1000000007;
//ll MOD = 998244353;

vector<ll> dy = {0, 0, 1, -1, 1, 1, -1, -1, 0};
vector<ll> dx = {1, -1, 0, 0, 1, -1, 1, -1, 0};

ll pow_long(ll x, ll k){
  ll res = 1;
  while(k > 0){
    if(k % 2) res *= x;
    x *= x;
    k /= 2;
  }
  return res;
}
ll pow_mod(ll x, ll k){
  x %= MOD; x += MOD; x %= MOD;
  ll res = 1;
  while(k > 0){
    if(k % 2){
      res *= x; res %= MOD;
    }
    x *= x; x %= MOD;
    k /= 2;
  }
  return res;
}

ll inverse(ll x){return pow_mod(x, MOD - 2);};

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

ll lcm(ll x, ll y){return x / gcd(x, y) * y;};

ll kai_mod(ll x){
  if(x == 0) return 1;
  return x * kai_mod(x-1) % MOD;
}

/*
//コンビネーション
const int MAXcomb = 200010;
ll fac[MAXcomb], finv[MAXcomb], inv[MAXcomb];
//facはn!,finvは1/n!
//invは逆元
void COMinit(){
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for(int i = 2; i < MAXcomb; i++){
        fac[i] = fac[i-1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD/i) % MOD;
        finv[i] = finv[i-1] * inv[i] % MOD;
    }
}
ll comb(int n, int k){
    if(n < k) return 0;
    if(n < 0 || k < 0) return 0;
    return fac[n] * finv[k] % MOD * finv[n-k] % MOD;
}
*/

ll N, M;
vector<ll> A, B;
void solve(){
  ll ans = 1;
  sort(A.begin(), A.end());
  reverse(A.begin(), A.end());
  A.pb(-1);
  sort(B.begin(), B.end());
  reverse(B.begin(), B.end());
  rep(i, N-1)if(A[i] == A[i+1]) ans = 0;
  rep(i, M-1)if(B[i] == B[i+1]) ans = 0;
  B.pb(-1);
  ll a = 0, b = 0;
  for(ll i = N * M; i >= 1; i--){
    if(A[a] == i && B[b] == i){
      ans *= 1;
      a++, b++;
    }else if(A[a] == i){
      ans *= b;
      a++;
    }else if(B[b] == i){
      ans *= a;
      b++;
    }else{
      ans *= a * b - (N*M-i);
    }
    ans %= MOD;
  }
  cout << ans << endl;
}
int main(){
  cin >> N >> M;
  A.resize(N);
  B.resize(M);
  rep(i, N) cin >> A[i];

  rep(i, M) cin >> B[i];

  solve();
}


#include "bits/stdc++.h"
#define int long long
#define endl '\n'
using namespace std;

typedef long long ll;
#define db(x) cerr << #x << ": " << x << '\n';
#define read(a) int a; cin >> a;
#define readb(a, b) int a, b; cin >> a >> b;
#define readc(a, b, c) int a, b, c; cin >> a >> b >> c;
#define readarr(a, n) int a[(n) + 1] = {}; FOR(i, 1, (n)) {cin >> a[i];}
#define readmat(a, n, m) int a[n + 1][m + 1] = {}; FOR(i, 1, n) {FOR(j, 1, m) cin >> a[i][j];}

#define print(a) cout << a << endl;
#define printarr(a, n) FOR (i, 1, n) cout << a[i] << " "; cout << endl;
#define printv(v) for (int i: v) cout << i << " "; cout << endl;
#define printmat(a, n, m) FOR (i, 1, n) {FOR (j, 1, m) cout << a[i][j] << " "; cout << endl;} cout << endl;
#define all(v) v.begin(), v.end()
#define sz(v) (int)(v.size())
#define rz(v, n) v.resize((n) + 1);
#define pb push_back
#define fi first
#define se second
#define vi vector <int>
#define pi pair <int, int>
#define vpi vector <pi>
#define vvi vector <vi>
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
const ll inf = 1e18;
const ll mod = 1e9 + 7;
const ll N = 2e5 + 1;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

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

	readc(n, h, w);
	int cnt = 0;
	FOR (i, 1, n)
	    FOR (j, 1, n)
	        if (i + h - 1 <= n && j + w - 1 <= n) cnt++;

	        print(cnt);
}

#include <bits/stdc++.h>
#define rep(a,n) for (ll a = 0; a < (n); ++a)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<vector<ll> > Graph;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const ll INF = 1e18;

int main(){
    ll n,h,w;
    cin >> n >> h >> w;
    cout << (n-h+1)*(n-w+1) << endl;
    return 0;
}


#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <math.h>
#include <stdexcept>
#include <algorithm>
#include <set>
#include <map>
#include <stdlib.h>
#include <cctype>
#include <bitset>
using namespace std;
int main()
{
    int N;
    cin >> N;
    cout << (N - (N % 3)) / 3 << endl;
}

#include<bits/stdc++.h>
using namespace std;
int main(){
  int64_t ans=1;
  int m,j,k,y,mod=1e9+7;
  bool f;
  cin>>m;
  vector<int> p={2};
  for(j=3;j<=m;j+=2){
    f=true;
    for(k=0;k<(int)p.size();k++){
      if(j%p.at(k)==0){
        f=false;
        break;
      }
    }
    if(f==true) p.push_back(j);
  }
  int l=p.size();
  vector<int> x(l);
  for(j=2;j<=m;j++){
    y=j;
    for(k=0;k<l;k++){
      while(y%p.at(k)==0){
        x.at(k)++;
        y/=p.at(k);
      }
      if(y==1) break;
    }
  }
  for(auto z:x) ans=ans*(z+1)%mod;
  cout<<ans<<endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(i, n) for (ll i = 0; i < n; i++)
#define FOR(i, a, b) for (ll i = a; i < b; i++)
#define len(v) ll(v.size())
#define fi first
#define se second

template <class T>
void cout_vec(const vector<T> &vec){
  for(auto itr:vec) cout<<itr<<' ';
  cout<<endl;
}

typedef pair<ll,ll> P;
const ll mod=1e9+7;
const ll inf=1e15;

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n,x,y,z;
  cin>>n>>x>>y>>z;
  vector<vector<int>> dp(n+1,vector<int>((1<<(x+y+z-1)),0));
  int mask=(1ll<<(x+y+z-1))-1;
  int ng=(1<<(x+y+z-1))|(1<<(y+z-1))|(1<<(z-1));
  dp[0][0]=1;
  rep(i,n){
    rep(S,1<<(x+y+z-1)){
      if((S & ng)==ng) continue;
      FOR(j,1,11){
        int T=(S<<j) | (1<<(j-1));
        if((T & ng)==ng) continue;
        T&=mask;
        (dp[i+1][T]+=dp[i][S])%=mod;
      }
    }
  }
  ll ans=1;
  rep(i,n) (ans*=10)%=mod;
  rep(i,1<<(x+y+z-1)) (ans-=dp[n][i])%=mod;
  cout<<(ans+mod)%mod<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) REP(i,0,n)
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define repr(i, n) REPR(i, n, 0)
#define REPR(i, s, e) for(int i=(int)(s-1); i>=(int)(e); i--)
#define pb push_back
#define all(r) r.begin(),r.end()
#define rall(r) r.rbegin(),r.rend()
#define fi first
#define se second

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const ll INF = 1e9;
const ll MOD = 1e9 + 7;
const double EPS = 1e-8;

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

ll modPow(ll x, ll n) {
    ll ret = 1;
    while(n) {
        if(n&1LL) (ret *= x) %= MOD;
        n >>= 1;
        (x *= x) %= MOD;
    }
    return ret;
}

ll dp[41][(1<<17)+10];

int main(){
    int n;
    vi v(3);
    cin >> n;
    rep(i, 3) cin >> v[i];
    int sum_v = v[0] + v[1] + v[2];
    dp[0][0] = 1;
    auto check = [&](int mask) {
        bool f = true;
        f &= (mask >>=(v[2]-1)) & 1;
        f &= (mask >>=v[1]) & 1;
        f &= (mask >>=v[0]) & 1;
        return f;
    };
    auto pop_mask = [&](int mask) {
        if(mask == 0) return 0;
        bool f = true;
        repr(i, sum_v) {
            if(mask & (1<<i)) {
                if(f) {
                    mask -= (1<<i);
                    f = false;
                    break;
                }
            }
        }
        return mask;
    };
    auto getSize = [&](int mask) {
        if(mask == 0) return 0;
        repr(i, sum_v) {
            if(mask&(1<<i)) {
                return i+1;
            }
        }
        return 0;
    };
    auto push_mask = [&](int mask, int add) {
        if(add > sum_v) return 0;
        while(getSize(mask)+add > sum_v) {
            mask = pop_mask(mask);
        }
        mask <<= add;
        mask |= 1<<(add-1);
        return mask;
    };
    rep(i, n) rep(mask, 1<<sum_v) {
        REP(k, 1, 11) {
            int nxt = push_mask(mask, k);
            if(check(mask) || check(nxt)) continue;
            (dp[i+1][nxt] += dp[i][mask]) %= MOD;
        }
    }
    ll sum = 0LL;
    rep(mask, 1<<sum_v) (sum += dp[n][mask]) %= MOD;
    ll ans = modPow(10, n);
    (ans += MOD - sum) %= MOD;
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(ll i=0;i<n;i++)
#define repl(i,l,r) for(ll i=(l);i<(r);i++)
#define per(i,n) for(ll i=n-1;i>=0;i--)
#define perl(i,r,l) for(ll i=r-1;i>=l;i--)
#define fi first
#define se second
#define pb push_back
#define ins insert
#define all(x) (x).begin(),(x).end()
using ll=long long;
using vl=vector<ll>;
using vvl=vector<vector<ll>>;
const ll MOD9=1000000007;
const ll MOD=998244353;
const int inf=1e9+10;
const ll INF=4e18;
const ll dy[8]={1,0,-1,0,1,1,-1,-1};
const ll dx[8]={0,-1,0,1,1,-1,1,-1};
using Graph = vector<vector<int>>;
double nCk(int n, int k) {
double res=1.0;
for(int i=0; i<n; i++){
res*=0.5;}
for(int i=0; i<k; i++){
res*=(double)(n-i);
res/=(double)(k-i);
}
return res;}
struct edge{ll to, cost;};
typedef pair<ll,ll> P;
struct graph{
  ll V;
  vector<vector<edge> > G;
  vector<ll> d;

  graph(ll n){
    init(n);
  }

  void init(ll n){
    V = n;
    G.resize(V);
    d.resize(V);
    rep(i,V){
      d[i] = INF;
    }
  }

  void add_edge(ll s, ll t, ll cost){
    edge e;
    e.to = t, e.cost = cost;
    G[s].push_back(e);
  }

  void dijkstra(ll s){
    rep(i,V){
      d[i] = INF;
    }
    d[s] = 0;
    priority_queue<P,vector<P>, greater<P> > que;
    que.push(P(0,s));
    while(!que.empty()){
      P p = que.top(); que.pop();
      ll v = p.second;
      if(d[v]<p.first) continue;
      for(auto e : G[v]){
        if(d[e.to]>d[v]+e.cost){
          d[e.to] = d[v]+e.cost;
          que.push(P(d[e.to],e.to));
        }
      }
    }
  }
};
class UnionFind
{
public:
  int par[100005];
  int depth[100005];
  int nGroup[100005];

  UnionFind(int n) {
    init(n);
  }

  void init(int n) {
    for(int i=0; i<n; i++) {
      par[i] = i;
      depth[i] = 0;
      nGroup[i] = 1;
    }
  }

  int root(int x) {
    if(par[x] == x) {
      return x;
    } else {
      return par[x] = root(par[x]);
    }
  }

  bool same(int x, int y) {
    return root(x) == root(y);
  }

  void unite(int x, int y) {
    x = root(x);
    y = root(y);
    if(x == y) return;

    if(depth[x] < depth[y]) {
      par[x] = y;
      nGroup[y] += nGroup[x];
      nGroup[x] = 0;
    } else {
      par[y] = x;
      nGroup[x] += nGroup[y];
      nGroup[y] = 0;
      if(depth[x] == depth[y])
        depth[x]++;
    }
  }
};
const ll MAX = 510000;
ll fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
ll COM(ll n, ll k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

vector<ll> depth;
vector<ll> f;
vector<ll> g;
void dfs(const Graph &G, ll v, ll p, ll d) {
    depth[v] = d;
    for (auto nv : G[v]) {
        if (nv == p) continue; // nv が親 p だったらダメ
        dfs(G, nv, v, d+1);
    }

    // 帰りがけ時に、部分木サイズを求める
    f[v] = 1;
    g[v] = 1;// 自分自身
    for (auto c : G[v]) {
        if (c == p) continue;
        f[v]*=g[c];
        f[v]%=MOD;
        g[v]*=f[c];
        g[v]%=MOD;
        }
    f[v]+=g[v];
    f[v]%=MOD;
}

int main() {
ll n,m,k; cin>>n>>m>>k;
ll ca = 0;
ll q = 1;
COMinit();
for(ll i=0; i<n-k-1; i++){
q*=m-1;
q%=MOD;}
q*=m;
q%=MOD;
for(ll i=k; i>0; i--){
ll c = 1;
c*=(COM(n-1,i))%MOD;
//c*=m;
//c%=MOD;
c*=q;
c%=MOD;
q*=(m-1);
q%=MOD;
ca+=c;
ca%=MOD;}
//cout << q << endl;
//q*=m;
//q%=MOD;
//cout << q << endl;
ca+=q;
ca%=MOD;
//ll p = 1;
//for(ll i =1; i<100; i++){
//p*=99;
//p%=MOD;
//}
//cout << p << endl;
//p*=100;
//p%=MOD;
cout << ca << endl;}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using vl = vector<ll>;
using vll = vector<vl>;
using Pll = pair<ll, ll>;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(v) v.begin(), v.end()
#define sz(x) ((int) x.size())
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define F first
#define S second
const int MOD = 1e9+7;
const int INF = 2e9;
template<class T> void print(const T& t){ cout << t << endl; }
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; }
int gcd(int a,int b){return b?gcd(b,a%b):a;}

int main(){
  ll a, b, k;
  cin >> a >> b >> k;
  ll count = 0;
  while(count<k){
    if(a%2==1){
      a--;
    }
    b += a / 2;
    a /= 2;
    count++;
    if(count==k){
      break;
    }
    if(b%2==1){
      b--;
    }
    a += b / 2;
    b /= 2;
    count++;
  }
  cout << a << " " << b << endl;
}


#include <bits/stdc++.h>
#define pb push_back
#define pll pair <ll, ll>
#define mp make_pair
#define pyshnapyshnakaa ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define x first
#define y second
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#define plll pair <pair <ll, ll>, ll>
#define pllll pair <pair <ll, ll>, pair <ll, ll> >
#define psl pair <string, ll>
#define all(a) a.begin(), a.end()

typedef long long ll;

typedef long double ld;

using namespace std;

ll n, m, k, t;

const ll maxn = 6e3 + 100;
const ll shift = 2e3;

ll mod;

inline ll step(ll a, ll x) {
    if (x == 0) {
        return 1;
    }
    if (x % 2 == 1) {
        return step(a, x - 1) * a % mod;
    }
    ll t = step(a, x / 2);
    return t * t % mod;
}

inline ll del(ll a, ll b) {
    return a * step(b, mod - 2) % mod;
}

ll D[maxn][2 * maxn + 200]; /// s, 1 - 2

ll F[maxn];

ll R[maxn];

int main() {
    ll q, w, e, a, b, d;
    cin >> n >> mod;
    n *= 3;
    for (q = 1; q <= n; q++) {
        R[q] = del(1, q);
    }
    F[0] = 1;
    for (q = 1; q < maxn; q++) {
        F[q] = (F[q - 1] * q) % mod;
    }
    D[0][shift] = F[n];
    for (q = 0; q < n; q++) {
        for (w = 0; w < maxn * 2 + 100; w++) {
            for (e = 1; e <= 3; e++) {
                ll nw = w;
                if (e == 1) {
                    nw = nw + 1;
                }
                if (e == 2) {
                    nw = nw - 1;
                }
                if (q + e > maxn || nw > 3 * maxn || q + e < 0 || nw < 0) {
                    continue;
                }
                // D[q + e][nw] += del(D[q][w], q + e);
                D[q + e][nw] += D[q][w] * R[q + e] % mod;
                D[q + e][nw] %= mod;
            }
        }
    }
    ll ans = 0;
    for (q = 0; q < 2 * maxn + 200; q++) {
        if (q - shift >= 0) {
            ans += D[n][q];
            ans %= mod;
        }
    }
    cout << ans;
    return 0;
}

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
int main()
{
    int x,y;
    cin >> x >> y;
    int ans = 0;
    if(x < 4)
    {
        ans += (4 - x) * 100000;
    }
    if(y < 4)
    {
        ans += (4 - y) * 100000;
    }
    if(x == 1 && y == 1)
    {
        ans += 400000;
    }
    cout << ans << "\n";
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define rep(i, n) for(int i=0;i<(n);++i)
#define per(i, n) for(int i=(n)-1;i>=0;--i)
#define repa(i, n) for(int i=1;i<(n);++i)
#define foreach(i, n) for(auto &i:(n))
#define pii pair<int, int>
#define pll pair<long long, long long>
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
const ll MOD = (ll)1e9+7;
const ll INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
using namespace std;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}

ll modpow(ll x, ll b){
	ll res = 1;
	while(b){
		if(b&1)res = res * x % MOD;
		x = x * x % MOD;
		b>>=1;
	}
	return res;
}

ll modinv(ll x){
	return modpow(x, MOD-2);
}

int main(){
	int n;
	cin >> n;
	vector<vector<ll>> citys(n, vector<ll>(2));
	foreach(i, citys){
		foreach(j, i)cin>>j;
	}

	vector<vector<pll>> roads(n);

	rep(i, 2){
		vector<pll> line;
		rep(j, n){
			line.emplace_back(citys[j][i], j);
		}
		sort(all(line));
		rep(j, n-1){
			pll a = line[j];
			pll b = line[j+1];
			roads[a.second].emplace_back(abs(a.first-b.first), b.second);
			roads[b.second].emplace_back(abs(a.first-b.first), a.second);
		}
	}

	vector<bool> used(n, false);
	priority_queue<pll, vector<pll>, greater<pll>> pq;
	ll ans = 0;
	pq.emplace(0, 0);
	while(pq.size()){
		pll d = pq.top();
		pq.pop();
		if(used[d.second])continue;
		used[d.second] = true;
		ans += d.first;
		foreach(i, roads[d.second]){
			if(used[i.second])continue;
			pq.push(i);
		}
	}

	cout << ans << endl;

	return 0;
}

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<set>
#include<queue>
#include<stack>
using namespace std;
#define int long long
#define vel vector<long long>
#define vvel vector<vel>
#define rep(i,n) for(long long i=0;i<n;i++)
#define rp(i,n) for(long long i=1;i<n;i++)
#define sor(v) sort(v.begin(),v.end())
#define mmax(a,b) a=max(a,b)
#define mmin(a,b) a=min(a,b)
#define mkp make_pair
#define pin pair<int,int>
#define V vector
long long p = 1000000007;
vel rui(19, 1);
vel par;
int root(int ser) {
	if (par[ser] == -1) { return ser; }
	int ans = root(par[ser]);
	par[ser] = ans;
	return ans;
}
bool marge(pin a) {
	int x = root(a.first);
	int y = root(a.second);
	if (x != y) {par[x] = y;}
	return x != y;
}
signed main() {
	int n; cin >> n;
	vel x(n), y(n);
	V<pair<pin, int>> xy(n);
	V<pair<pin, int>> yx(n);
	rep(i, n) {
		cin >> x[i] >> y[i];
		xy[i] = mkp(mkp(x[i], y[i]), i);
		yx[i] = mkp(mkp(y[i], x[i]), i);
	}
	sor(xy); sor(yx);
	V<pair<int, pin>> way(0);
	rep(i, n - 1) {
		int diff = xy[i + 1].first.first - xy[i].first.first;
		pin path = mkp(xy[i].second, xy[i+1].second);
		way.push_back(mkp(diff, path));
	}
	rep(i, n - 1) {
		int diff = yx[i + 1].first.first - yx[i].first.first;
		pin path = mkp(yx[i].second, yx[i + 1].second);
		way.push_back(mkp(diff, path));
	}
	sor(way);
	int ans = 0;
	par = vel(n, -1);
	rep(i, way.size()) {
		if (marge(way[i].second)) { ans += way[i].first; }
	}
	cout << ans << endl;
	return 0;
}


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

int main(){
 int a;
 cin>>a;
 int ans =0;
 for(int i=0;i<3;i++){
   ans+=pow(a,i+1);
 }
 cout<<ans<<endl;
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int mod = 1000000007;

int main() {
    ios::sync_with_stdio(false);
    int a;
    cin >> a;
    cout << a + a * a + a * a * a;
}


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

int main(){
  int sx, sy, tx, ty;
  cin >> sx >> sy >> tx >> ty;
  string ans;
    rep(i,ty-sy) ans+='U';
    rep(i,tx-sx) ans+='R';
    rep(i,ty-sy) ans+='D';
    rep(i,tx-sx) ans+='L';
    ans+='L';
    rep(i,ty-sy+1) ans+='U';
    rep(i,tx-sx+1) ans+='R';
    ans+='D';
    ans+='R';
    rep(i,ty-sy+1) ans+='D';
    rep(i,tx-sx+1) ans+='L';
    ans+='U';
  cout<<ans<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define REP(i, d, n) for(int i=(d); i<(n); ++i)
#define all(v) v.begin(), v.end()
using ll = long long;
using P = pair<int, int>;

int main() {

	int n;
	cin >> n;
	vector<double> a(n);
	double sum = 0;
	rep(i, n){
		cin >> a[i];
		sum += a[i];
	}

	double k = sum / n;
	double mi = 100000;
	int ans = 0;
	rep(i, n){
		if(mi > abs(a[i]-k)){
			mi = abs(a[i]-k);
			ans = i;
		}
	}
	cout << ans << endl;

    return 0;
}


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

int main() {
  int d, t, s;
  cin >> d >> t >> s;
  string ans;
  if((double)d/s <= t){
    ans = "Yes";
  }else{
    ans = "No";
  }
  cout << ans << endl;

}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const ll MOD = 1e9+7;
#define REP(i,j,n) for(int i=j;i<n;i++)
#define rep(i,n) REP(i,0,n)

// Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    int d,t,s;
    cin >> d >> t >> s;

    if (d <= t * s)
    {
        cout << "Yes" << endl;
    }
    else
    {
        cout << "No" << endl;
    }

}


#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <tuple>
#include <iomanip>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vec;
typedef vector<vec> mat;
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define revrep(i, n) for(ll i = (n)-1; i >= 0; i--)
#define pb push_back
#define f first
#define s second
ll max(ll a, ll b){return (a > b) ? a : b;}
ll min(ll a, ll b){return (a < b) ? a : b;}
ll max3(ll a, ll b, ll c){return max(a, max(b, c));};
ll min3(ll a, ll b, ll c){return min(a, min(b, c));};
ll max4(ll a, ll b, ll c, ll d){return max(max(a, b), min(c, d));};
ll min4(ll a, ll b, ll c, ll d){return min(min(a, b), min(c, d));};
ll max5(ll a, ll b, ll c, ll d, ll e){return max(max(a, b), max3(c, d, e));};
ll min5(ll a, ll b, ll c, ll d, ll e){return min(min(a, b), min3(c, d, e));};

const ll INFL = 1LL << 60;//10^18 = 2^60
const int INF = 1 << 30;//10^9
ll MOD = 1000000007;
//ll MOD = 998244353;

vector<ll> dy = {0, 0, 1, -1, 1, 1, -1, -1, 0};
vector<ll> dx = {1, -1, 0, 0, 1, -1, 1, -1, 0};

ll pow_long(ll x, ll k){
  ll res = 1;
  while(k > 0){
    if(k % 2) res *= x;
    x *= x;
    k /= 2;
  }
  return res;
}
ll pow_mod(ll x, ll k){
  x %= MOD; x += MOD; x %= MOD;
  ll res = 1;
  while(k > 0){
    if(k % 2){
      res *= x; res %= MOD;
    }
    x *= x; x %= MOD;
    k /= 2;
  }
  return res;
}

ll inverse(ll x){return pow_mod(x, MOD - 2);};

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

ll lcm(ll x, ll y){return x / gcd(x, y) * y;};

ll kai_mod(ll x){
  if(x == 0) return 1;
  return x * kai_mod(x-1) % MOD;
}

/*
//コンビネーション
const int MAXcomb = 200010;
ll fac[MAXcomb], finv[MAXcomb], inv[MAXcomb];
//facはn!,finvは1/n!
//invは逆元
void COMinit(){
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for(int i = 2; i < MAXcomb; i++){
        fac[i] = fac[i-1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD/i) % MOD;
        finv[i] = finv[i-1] * inv[i] % MOD;
    }
}
ll comb(int n, int k){
    if(n < k) return 0;
    if(n < 0 || k < 0) return 0;
    return fac[n] * finv[k] % MOD * finv[n-k] % MOD;
}
*/

string S;
ll K;
ll memo[310][310][310];//[)
ll solve(ll l, ll r, ll rest){
  if(l > r) return -INFL;
  if(l == r) return 0;
  if(l + 1 == r) return 1;
  if(memo[l][r][rest] != -1) return memo[l][r][rest];
  ll res = max(solve(l, r-1, rest), solve(l+1, r, rest));
  if(S[l] == S[r-1]){
    res = max(res, solve(l+1, r-1, rest) + 2);
  }else{
    if(rest >= 1) res = max(res, solve(l+1, r-1, rest - 1) + 2);
  }
  return memo[l][r][rest] = res;
}

int main(){
  cin >> S >> K;
  rep(i, 310)rep(j, 310)rep(k, 310) memo[i][j][k] = -1;
  cout << solve(0, S.size(), K) << endl;
}

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<ctime>
#include<map>
#include<bitset>
#include<set>
#include<assert.h>
#define LL long long
#define mp(x,y) make_pair(x,y)
#define pll pair<long long,long long>
#define pii pair<int,int>
#define SZ(x) ((int)x.size())
using namespace std;
inline LL read()
{
	LL f=1,x=0;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
int stack[20];
template<typename T>inline void write(T x)
{
	if(x<0){putchar('-');x=-x;}
    if(!x){putchar('0');return;}
    int top=0;
    while(x)stack[++top]=x%10,x/=10;
    while(top)putchar(stack[top--]+'0');
}
template<typename T>inline void pr1(T x){write(x);putchar(' ');}
template<typename T>inline void pr2(T x){write(x);putchar('\n');}
template<typename T>inline void chkmin(T &x,T y){x=x<y?x:y;}
template<typename T>inline void chkmax(T &x,T y){x=x>y?x:y;}
const int MAXN=305;
int f[MAXN][MAXN][MAXN],n,K;char ch[MAXN];
int main()
{
	scanf("%s",ch+1);n=strlen(ch+1);K=read();
	f[0][n+1][0]=0;int ans=0;
	for(int i=0;i<=n;i++)for(int j=n+1;j>=i;j--)for(int k=0;k<=K;k++)
	{
		int ad=(ch[i]==ch[j]?0:1);
		if(i-1>=0)chkmax(f[i][j][k],f[i-1][j][k]);
		if(j+1<=n+1)chkmax(f[i][j][k],f[i][j+1][k]);
		if(i-1>=0&&j+1<=n+1&&k-ad>=0)chkmax(f[i][j][k],f[i-1][j+1][k-ad]+1);
		if(i<j)chkmax(ans,2*f[i][j][k]);
		else chkmax(ans,2*f[i][j][k]-1);
	}pr2(ans);
	return 0;
}


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

typedef long long ll;
#define rep(i,x) for(int i=0;i<x;i++)
#define put(ans)    cout << ans << endl;

double kaijyo(int n){
    int k(1);
    for(int i=n;i>0;i--){
        k *= i;
    }

    return k;
}

double distance(int x[],int y[],int i,int j){
    int dx = (x[i] - x[j]) * (x[i] - x[j]);
    int dy = (y[i] - y[j]) * (y[i] - y[j]);
    return sqrt(dx+dy);
}

int main(){
    string s,t;
    cin >> s >> t;
    cout << t << s << endl;

    return 0;
}

#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define INF 2e9
#define ALL(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
int main()
{
  ll n,Y; cin >> n >> Y;
  ll sum;
  REP(i,n+1){
    REP(j,n-i+1){
      int k = n - i - j;
      sum = 10000 * i + 5000 * j + 1000 * k;
      if(sum == Y){
        printf("%d %d %d",i,j,k);
        return 0;
      }
    }
  }
  printf("-1 -1 -1");
}


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

struct FenwickTree {
    vector<int> bit;  // binary indexed tree
    int n;

    FenwickTree(int n) {
        this->n = n;
        bit.assign(n, 0);
    }

    FenwickTree(vector<int> a) : FenwickTree(a.size()) {
        for (size_t i = 0; i < a.size(); i++)
            add(i, a[i]);
    }

    int sum(int r) {
        int ret = 0;
        for (; r >= 0; r = (r & (r + 1)) - 1)
            ret += bit[r];
        return ret;
    }

    int sum(int l, int r) {
        return sum(r) - sum(l - 1);
    }

    void add(int idx, int delta) {
        for (; idx < n; idx = idx | (idx + 1))
            bit[idx] += delta;
    }
};

int main() {
	const int MAXN = 200000;
	int a[MAXN],  b[MAXN]={0};
	int n, k;
	cin>>n>>k;
	for(int i=0;i<n;i++) cin>>a[i];
	const int iterations = 41;
	for(int i=1;i<=min(k, iterations);i++) {
		FenwickTree t1(n), t2(n);
		for(int j=0;j<n;j++) {
			b[j] += t1.sum(j, n-1);
			t1.add(min(n-1,j+a[j]), 1);
		}
		for(int j=n-1;j>=0;j--) {
			t2.add(max(0,j-a[j]), 1);
			b[j] += t2.sum(j);
		}
		for(int j=0;j<n;j++) {
			a[j]=b[j];
			b[j]=0;
		}
	}
	for(int i=0;i<n;i++) cout<<a[i]<<" ";
	cout<<endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define rep(i,N) for(ll (i)=0;(i)<(N);(i)++)
const int mod = 1000000007;

int main() {
  int n, q;
  cin >> n >> q;
  vector<tuple<int, int, int>> a(n);
  rep(i, n) {
    int s, t, x;
    cin >> s >> t >> x;
    s -=x;
    t -= x;
    a[i] = tie(x, s, t);
  }
  sort(a.begin(), a.end());

  set<P> st;
  rep(i, q) {
    int d;
    cin >> d;
    st.insert(P(d, i));
  }
  vector<int> ans(q, -1);
  rep(i, n) {
    int s, t, x;
    tie(x, s, t) = a[i];
    auto it = st.lower_bound(P(s, -1));
    while(it != st.end()) {
      if(it->first >= t) break;
      ans[it->second] = x;
      st.erase(it++);
    }
  }
  rep(i, q) {
    cout << ans[i] << endl;
  }

}


#include <iostream>
#include <cstdint>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <cassert>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
#include <unordered_set>
#pragma GCC optimize("Ofast")
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define mes(a) cout << (a) << endl
#define dmes(a, b) cout << (a) << " " << (b) << endl
#define re0 return 0
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define rSort(a) sort(a.rbegin(), a.rend())
#define MATHPI acos(-1)
#define itn int;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
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;
}
struct io
{
    io()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
    }
};
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
const ll MOD = 1000000007;
const double EPS = 1e-9;

bool isPrime(ll x){
    ll i;
    if(x < 2)return 0;
    else if(x == 2) return 1;
    if(x%2 == 0) return 0;
    for(i = 3; i*i <= x; i += 2) if(x%i == 0) return 0;
    return 1;
}

signed main(void)
{
    ll l, r;
    cin >> l >> r;
    ll ans = 2020;

    if (r-l > 2020) {
        mes(0);
        re0;
    }

    for(ll i = l; i < r; i++) {
        for (ll j = i+1; j <= r; j++) {
            ans = min(ans, (i*j)%2019);
        }
    }
    mes(ans);

}

#include <bits/stdc++.h>
typedef long long int ll;
typedef long double ld;
using namespace std;
const long long int INF = 1e18;
const long long int mod = 1e9+7;
typedef pair<ll,ll> pairs;
vector<pairs> p;

ll gcd(ll A,ll B){
    if (A%B==0)return(B);
    else return(gcd(B,A%B));
}

ll keta(ll N){
    int tmp{};
    while( N > 0 ){
        tmp += ( N % 10 );
        N /= 10;
    }
    N = tmp;
    return N;
}

vector<vector<ll>> combination(ll n, ll r){
    vector<vector<ll>> v(n + 1, vector<ll>(n + 1, 0));
    for(ll i=0;i<v.size();++i){
        v[i][0] = 1;
        v[i][i] = 1;
    }
    for(ll i=1;i<v.size();++i){
        for(ll j=0;j<i;++j){
            v[i][j] = (v[i - 1][j - 1] + v[i - 1][j]);
        }
    }
    return v;
}

bool kai(string S){
    bool flag = true;
    for(ll i=0;i<S.size()/2;++i){
        if(S[i] != S[S.size()-i-1]){
            flag = false;
            break;
        }
    }
    return flag;
}
// ---------------------------------------------

int main(){
    string s;
    cin>>s;
    ll w;
    cin>>w;
    for(ll i=0;i<s.size();i+=w){
        cout<<s[i];
    }
    cout<<endl;

    return 0;
}


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

int main(void) {
    int a,b,c,k;
    int64_t target;
    int64_t remains;
    cin >> a >> b >> c >> k;
    target = max(a,max(b,c));
    remains = a + b + c - target;
    target = target * pow(2,k);
    cout << target + remains << endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
    double n, x, t;
    cin>>n>>x>>t;
    double t1 = ceil(double(n/x));
    //cout<<n/x<<endl;
    //cout<<t1<<endl;
    ll t11 = ll(t1)*ll(t);
    cout<<t11<<endl;

}


#include <iostream>
#include <iomanip>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <bitset>
#include <set>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define RREP(i,n) for(int i=n-1;i>=0;i--)
#define FOR(i,k,n) for(int i=(k);i<(int)(n);i++)
#define all(i,n) (i),(i+n)

int dx4[4]={1,0,-1,0};
int dy4[4]={0,-1,0,1};
int dx8[8]={1,0,-1,1,-1,1,0,-1};
int dy8[8]={1,1,1,0,0,-1,-1,-1};
int dx9[9]={0,1,0,-1,1,-1,1,0,-1};
int dy9[9]={0,1,1,1,0,0,-1,-1,-1};

typedef pair<int, int> P;
typedef pair<string, int> SP;
typedef long long ll;
typedef pair<ll, ll> PLL;

const int INF = 1e9;
const ll LLINF = 1e18;
const int MAX_V = 1e6+1;
const ll mod = 1000000007;
// << fixed << setprecision
// --------------------------------------
int n, q;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin >> n >> q;
  set<P> vp;
  vector<tuple<int, int, int>> ve;

  REP(i, n) {
    int l, r, x;
    cin >> l >> r >> x;
    l -= x; r -= x;
    ve.push_back(tie(x, l, r));
  }

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

  REP(i, q) {
    int d;
    cin >> d;
    vp.insert(P(d, i));
  }

  vector<int> ans(q, -1);
  REP(i, n) {
    int x, l, r;
    tie(x, l, r) = ve[i];

    auto it = vp.lower_bound(P(l, -1));
    while(it != vp.end()) {
      if(it->first >= r) break;
      ans[it->second] = x;
      vp.erase(it++);
    }
  }

  REP(i, q) cout << ans[i] << endl;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int, int> duo;

#define TT template<typename T>
TT T    sq(T x){ return x*x; }
TT int  ubnd(vector<T>& v,T x){ return upper_bound(v.begin(), v.end(), x) - v.begin(); }
TT int  lbnd(vector<T>& v,T x){ return lower_bound(v.begin(), v.end(), x) - v.begin(); }
TT void sort(T& v){ sort(v.begin(), v.end()); }
TT void revs(T& v){ reverse(v.begin(), v.end()); }
TT void uniq(T& v){ sort(v); v.erase(unique(v.begin(), v.end()), v.end()); }
TT void show(T& v,char d=' ',char e='\n'){for(int i=0;i<v.size();++i)cout<<v[i]<<((i==v.size()-1)?e:d);}
TT void inpt(vector<T>& v,int n){ v.reserve(n);for(int i=0;i<n;++i){T x; cin>>x; v.push_back(x);} }
TT T    In(T& x){ cin >> x; return x; }

static inline void fast_io(){ ios::sync_with_stdio(0); cin.tie(0); }
static inline int in(){ int x; scanf("%d", &x); return x; }
static inline string instr(){ string x; cin >> x; return x; }
static const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
static const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};

struct Rect {
  int h, w, d;
  Rect(int h, int w) : h(h), w(w), d(sq(h) + sq(w)) {}
  bool operator<(const Rect& x) const {
    return d == x.d ? h < x.h : d < x.d;
  }
};

int main()
{
  vector<Rect> v;
  int h, w;
  for (int x = 1; x <= 150; x++){
    for (int y = 1; y < x; y++){
      v.push_back(Rect(y, x));
    }
  }
  sort(v);

  while (h = in(), w = in(), h || w){
    Rect r = Rect(h, w);
    int index = ubnd(v, r);
    printf("%d %d\n", v[index].h, v[index].w);
  }
  return (0);
}


#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define ll long long
#define rep2(i,a,b) for(ll i=a;i<=b;++i)
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep3(i,a,b) for(ll i=a;i>=b;i--)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pq priority_queue<int>
#define pb push_back
#define eb emplace_back
#define vec vector<int>
#define vecll vector<ll>
#define vecpii vector<pii>
#define vec2 vector<vec>
#define vecll2 vector<vecll>
#define vec3 vector<vec2d>
#define vecll3 vector<vecll2d>
#define fi first
#define se second
#define endl "\n"
#define all(c) begin(c),end(c)
#define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
int in() {int x;cin>>x;return x;}
ll lin() {ll x;cin>>x;return x;}
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> inline void print(vector<T> v){for(T e:v)cout<<e<<" ";cout<<endl;}
template<class T> inline void print(pair<T,T> p){cout<<"("<<p.first<<","<<p.second<<") ";}
template<class T> inline void print(vector<pair<T,T>> v){for(auto e:v)print(e); cout<<endl;}
void print(vector<vec> v){for(auto e:v){for(auto ee:e)cout<<ee<<" ";cout<<endl;}}
void print(map<int,int> mp){for(auto e:mp)cout<<e.first<<" "<<e.second<<endl;cout<<endl;}

int m[1100][1100];
int tmp[2200][2200];
int r1[2200][2200];
int r2[2200][2200];
main(){
    int n=in();
    vec a;rep(i,n)a.pb(in());
    int sum=0;
    rep(i,n)sum+=a[i];
    int d=INT_MAX;
    int ans;
    rep(i,n){
        if(abs(sum-a[i]*n)<d){
            d=abs(sum-a[i]*n);
            ans=i;
        }
    }
    cout<<ans<<endl;
}


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

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; }

using ll = long long;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int INF = 1<<30;
const ll mod = 1000000007LL;

int main() {
  string S;
  cin>>S;
  reverse(S.begin(),S.end());
  int l = S.size();
  int ans = 0;
  int over = 0;
  for(int i = 0; i < l; i++){
    int t = S[i]-'0';
    t+=over;
    over = 0;
    if(t>=10) {
      t-=10;
      over = 1;
    }
    if(t<=4) ans += t;
    if(t==5){
      int s;
      if(i!=l-1) s = S[i+1]-'0';
      if(i==l-1||s<=4) ans+=t;
      else if(s>=5) {
        ans+=(10-t);
        over=1;
      }
    }
    if(t>=6) {
      ans += (10-t);
      over = 1;
    }
    if(i==l-1&&over!=0) ans+=over;
  }
  cout<<ans<<endl;
}

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

ll dp[1000010][2];

int main(){
    string s; cin >> s;
    s = '0' + s;
    int n = s.size();
    dp[0][1] = 1;
    for(int i=1;i<n;i++){
        int c = s[i]-'0';
        dp[i][0] = min(dp[i-1][0]+c, dp[i-1][1]+(10-c) );
        dp[i][1] = min(dp[i-1][0]+c+1, dp[i-1][1]+(10-c-1));
    }
    cout << dp[n-1][0] << endl;
}


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

const long long mod = 1e9 + 7;

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

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

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

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

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

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

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

#include<bits/stdc++.h>
#include<boost/dynamic_bitset.hpp>
using namespace std;
using u64 = uint64_t;
using s64 = int64_t;

int main(void) {
    u64 N, M;
    cin >> N >> M;

    u64 lM = M / 2;
    u64 lN = N / 2;
    u64 rM = M - lM;
    u64 rN = N - lN;

    if(lN == rN) {
        lN--;
    }

    for(u64 i=0, l=1, r=lN; i<lM; i++, l++, r--) {
        cout << l << " " << r << endl;
    }

    for(u64 i=0, l=N/2+1, r=N; i<rM; i++, l++, r--) {
        cout << l << " " << r << endl;
    }

    return 0;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#include <tuple>
#include <utility>
#include <vector>
#define ll long long
#define double long double
#define itn int
#define endl '\n'
#define co(ans) cout<<ans<<endl
#define COYE cout<<"YES"<<endl
#define COYe cout<<"Yes"<<endl
#define COye cout<<"yes"<<endl
#define CONO cout<<"NO"<<endl
#define CONo cout<<"No"<<endl
#define COno cout<<"no"<<endl
#define FORE(i,a) for(auto &i:a)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define FFOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define RREP(i,n)  FFOR(i,1,n)
#define PB push_back
#define MP make_pair
#define ALL(V) (V).begin(),(V).end()
#define SORT(V) sort((V).begin(),(V).end())
#define REVERSE(V) reverse((V).begin(),(V).end())
#define EACH(V,i) for(typeof((V).begin()) i=(V).begin();i!=(V).end();++i)
#define INF ((1LL<<62)-(1LL<<31))
#define EPS 1e-10
#define PI 3.141592653589793238
#define MOD 1000000007
#define MAX 5100000
using namespace std;
using Graph=vector<vector<int>>;
inline int toInt(string s){int v;istringstream sin(s);sin>>v;return v;}
template<class T>inline string toString(T x){ostringstream sout;sout<<x;return sout.str();}
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;}
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
const int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
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(){
  int N,M,Q;
  cin>>N>>M>>Q;
  string SS[N+1];

  int S[N+1][M+1];
  int C[N+1][M+1]; // 横に連続する1のマスの総数
  int R[N+1][M+1]; // 縦に連続する1のマスの総数
  int SUM[N+1][M+1]; // 存在する1のマスの総数

  for(int i=1; i<=N; ++i){
    cin>>SS[i];
    for(int j=1; j<=M; ++j){
      if(SS[i][j-1]=='0') S[i][j]=0;
      else S[i][j]=1;
    }
  }

  for(int i=0; i<=N; ++i){
    for(int j=0; j<=M; ++j){
      if(i*j==0){
        S[i][j]=0;
        C[i][j]=0;
        R[i][j]=0;
        SUM[i][j]=0;
      }
    }
  }

  for(int i=1; i<=N; ++i){
    for(int j=1; j<=M; ++j){
      SUM[i][j]=SUM[i-1][j]+SUM[i][j-1]-SUM[i-1][j-1]+S[i][j];
      C[i][j]=C[i-1][j]+C[i][j-1]-C[i-1][j-1]+S[i][j];
      R[i][j]=R[i-1][j]+R[i][j-1]-R[i-1][j-1]+S[i][j];
      if(S[i][j]==1){
        if(S[i][j-1]==0) C[i][j]--;
        if(S[i-1][j]==0) R[i][j]--;
      }
    }
  }

  for(int i=1; i<=Q; ++i){
    int X,Y,XX,YY,ans=0;
    cin>>X>>Y>>XX>>YY;

    ans+=SUM[XX][YY]+SUM[X-1][Y-1]-SUM[X-1][YY]-SUM[XX][Y-1];
    ans-=R[XX][YY]+R[X][Y-1]-R[XX][Y-1]-R[X][YY];
    ans-=C[XX][YY]+C[X-1][Y]-C[X-1][YY]-C[XX][Y];

    co(ans);
  }

  return 0;
}

#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>

using namespace std;

int main() {
    while(true) {
        int N, K;
        cin >> N >> K;
        if(!N && !K) break;

        vector<vector<int> > v(N, vector<int>(N, -1));
        while(K--) {
            int cmd;
            cin >> cmd;
            if(cmd == 0) {
                int a, b;
                cin >> a >> b;
                --a; --b;
                cout << v[a][b] << endl;
            }
            else {
                int c, d, e;
                cin >> c >> d >> e;
                --c; --d;
                if(v[c][d] == -1 || e < v[c][d]) {
                    v[c][d] = v[d][c] = e;
                    for(int k = 0; k < 2; ++k) {
                        int mid = k ? c : d;
                        for(int i = 0; i < N; ++i) {
                            for(int j = 0; j < N; ++j) {
                                if(v[i][mid] != -1 && v[mid][j] != -1) {
                                    if(v[i][j] == -1) v[i][j] = v[i][mid]+v[mid][j];
                                    else v[i][j] = min(v[i][j], v[i][mid]+v[mid][j]);
                                    v[j][i] = v[i][j];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return 0;
}


#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;

int main()
{
    int n, q, m, d, dt, days[101];
    while(cin >> n >> q && n && q) {
        memset(days, 0, sizeof(days));
        for(int i = 0; i < n; i++) {
            cin >> d;
            for(int j = 0; j < d; j++) {
                cin >> dt;
                days[dt]++;
            }
        }
        int ans = 0;
        for(int i = 1; i <= 100; i++)
            if(days[i] >= q && days[i] > days[ans])
                ans = i;

        cout << ans << endl;
    }
}

#define _USE_MATH_DEFINES
#define INF 100000000

#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cctype>
#include <utility>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

int main(){
	int N,Q;
	while(~scanf("%d %d",&N,&Q)){
		if(N==0 && Q==0) break;
		map<int,int> freq;
		for(int i=0;i<N;i++){
			int num;
			scanf("%d",&num);

			for(int j=0;j<num;j++){
				int day;
				scanf("%d",&day);
				freq[day]++;
			}
		}

		int maxv=0;
		int min_day=INF;
		for(map<int,int>::iterator it = freq.begin(); it!=freq.end();it++){
			if(it->second >= Q){
				if(maxv < it->second){
					maxv = it->second;
					min_day=it->first;
				}
				else if(maxv == it->second){
					min_day=min(min_day,it->first);
				}
			}
		}

		printf("%d\n",min_day >= INF ? 0 : min_day);
	}
}


#include <stdio.h>
const long long int INF=100000000000000000;
int main(){
	int n,m,l,r,c;
	long long int g[110][110];
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++)for(int j=0;j<n;j++){
		if(i==j)g[i][j]=0;
		else g[i][j]=INF;
	}
	while(m--){
		scanf("%d%d%d",&l,&r,&c);
		g[l][r]=c;
	}
	for(int k=0;k<n;k++)for(int i=0;i<n;i++)for(int j=0;j<n;j++){
		if(g[i][k]==INF||g[k][j]==INF)continue;
	if(g[i][k]+g[k][j]<g[i][j])g[i][j]=g[i][k]+g[k][j];
	}
	for(int i=0;i<n;i++)if(g[i][i]<0){
	printf("NEGATIVE CYCLE\n");
	return 0;
	}
	for(int i=0;i<n;i++){
		if(g[i][0]==INF)printf("INF");
		else printf("%lld",g[i][0]);
		for(int j=1;j<n;j++){
			if(g[i][j]==INF)printf(" INF");
			else printf(" %lld",g[i][j]);
		}
		printf("\n");
	}
}

#include "bits/stdc++.h"
#define ll long long
#define lld long double
#define MOD 1000000007
#define inf 1000000007
#define pii pair<int,int>
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
// ll power(ll x,ll y, ll md=inf){ll res = 1;x%=md;while(y){if(y&1)res = (res*x)%md;x *= x; if(x>=md) x %= md; y >>= 1;}return res;}

using namespace std;

#define endl '\n'
// #define int ll

signed main() {
	fast;

	int h,w;
	cin>>h>>w;

	pii v[200002];
	for(int i=0;i<h;i++) cin>>v[i].f>>v[i].s;

	map<int,int> mp;
	for(int i=1;i<=w;i++) mp[i] = 0;

	map<int,int> mini = {{0,w}};

	for(int i=0;i<h;i++) {
		int r = v[i].s;

		auto it = mp.lower_bound(v[i].f);

		if(r==w) {
			while(it!=mp.end() && it->f <= r) {
				auto it1 = it++;
				auto it2 = mini.find(it1->s);
				if(it2->s==1) mini.erase(it2);
				else it2->s --;
				mp.erase(it1);
			}

			if(mini.size()==0) cout<<-1<<endl;
			else cout<<mini.begin()->f+i+1<<endl;
		}
		else {
			int mn = inf;

			while(it!=mp.end() && it->f <= r) {
				mn = min(mn, r+1-(it->f)+(it->s));
				auto it1 = it++;
				auto it2 = mini.find(it1->s);
				if(it2->s==1) mini.erase(it2);
				else it2->s --;
				mp.erase(it1);
			}

			if(mn<inf) {
				if(it!=mp.end() && it->f == r + 1) {
					if(it->s > mn) {
						auto it1 = mini.find(it->s);
						if(it1->s ==1) mini.erase(it1);
						else it1->s --;
						mini[mn]++;
						it->s = mn;
					}
				}
				else {
					mp.emplace_hint(it,r+1,mn);
					mini[mn]++;
				}
				cout<<mini.begin()->f+i+1<<endl;
			}
			else {
				if(mini.size()==0) cout<<-1<<endl;
				else cout<<mini.begin()->f+i+1<<endl;
			}

		}

	}
}