// based on http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=2784229#1
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <set>
#include <algorithm>
#include <array>
#include <complex>
#include <utility>
#include <map>
int needleX[4] = { -1,0,1,0 };
int needleY[4] = { 0,1,0,-1 };
bool dfs(int x, int y, int goalx, int goaly, std::vector<std::vector<bool>>&canGo) {
  if (x == goalx && y == goaly) { return true; }
  canGo[y][x] = false;
  for (int i = 0; i < 4; i++) {
    int next_x = x + needleX[i];
    int next_y = y + needleY[i];

    if (canGo[next_y][next_x]) {
      bool flag = dfs(next_x, next_y, goalx, goaly, canGo);
      if (flag)
        return true;
    }
  }
  return false;
}
int main(void) {
  int h, w, n;
  std::cin >> w >> h;
  std::vector<std::string> ans;
  while(!(h == 0 && w == 0)){
    int color=-1, orient, leftX, leftY;
    int sx, sy, gx, gy;
    std::cin >> sx >> sy >> gx >> gy;
    std::vector<std::vector<int>> board(h + 2, std::vector<int>(w + 2, 0));
    std::vector<std::vector<bool>> canGo(h + 2, std::vector<bool>(w + 2, false));
    std::cin >> n;
    int start = -1, goal = -1;
    for (int i = 0; i < n; i++) {
      std::cin >> color >> orient >> leftX >> leftY;

      if (orient == 0) {
        for (int j = 0; j <= 3; j++) {
          for (int k = 0; k <= 1; k++) {
            board[leftY + k][leftX + j] = color;
            if (leftX + j == sx && leftY + k == sy) {
              start = color;
            }
            else if (leftX + j == gx && leftY + k == gy) {
              goal = color;
            }
          }
        }

      }
      else {
        for (int j = 0; j <= 1; j++) {
          for (int k = 0; k <= 3; k++) {
            board[leftY + k][leftX + j] = color;
            if (leftX + j == sx && leftY + k == sy) {
              start = color;
            }
            else if (leftX + j == gx && leftY + k == gy) {
              goal = color;
            }
          }
        }
      }
    }

    // for (int i = 0; i <= h; i++) {
    //   for (int j = 0; j <= w; j++) {
    //     std::cerr << board[i][j] << " ";
    //   }
    //   std::cerr << std::endl;
    // }

    if (start != -1) {
      for (int i = 0; i <= h; i++) {
        for (int j = 0; j <= w; j++) {
          if (board[i][j] == start) {
            canGo[i][j] = true;
          }
        }
      }
    }

    if (start != goal || start == -1) {
      ans.push_back("NG");
      std::cin >> w >> h;
      continue;
    }

    bool result = dfs(sx, sy, gx, gy, canGo);
    if (result) { ans.push_back("OK"); }
    else { ans.push_back("NG"); }
    std::cin >> w >> h;
  }
  int anssize = ans.size();
  for (int i = 0; i < anssize; i++) {
    std::cout << ans[i] << std::endl;
  }
  return 0;
}

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

using namespace std;

#define fr first
#define sc second
#define pb push_back
#define mp make_pair
#define chmin(a,b) a=min(a,b)
#define chmax(a,b) a=max(a,b)
#define rep(i,x) for(ll i=0;i<x;++i)
#define rep1(i,x) for(ll i=1;i<=x;++i)
#define rrep(i,x) for(ll i=x-1;i>=0;--i)
#define rrep1(i,x) for(ll i=x;i>=1;--i)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define rev(a) reverse(all(a))

template<typename T> T get(){T a;cin >> a;return a;}

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

const int inf = 1e9;
const ll linf = 1e18;

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

    vi team(N), rnk(N);

    fill(all(team), 0); fill(all(rnk), 1);

    rep(i, (N*N-N)/2) {
        int a, b, c, d; cin >> a >> b >> c >> d;
        a--; b--;
        if (c > d) team[a]+=3;
        else if (d > c) team[b]+=3;
        else {team[a]++;team[b]++;}
    }

    rep(i, N) rep(j, N) {
        if (team[i] < team[j]) rnk[i]++;
    }

    rep(i, N) cout << rnk[i] << endl;
}


#include <stdio.h>
#include <algorithm>
using namespace std;
int a[200010];
long long f[200010];
long long g[200010];
long long get(int x) {
    if (x <= 0) return 0;
    return f[x];
}
int main() {
    int n, i;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
        if (i) g[i] = g[i-1];
        if (i%2==0) g[i]+= a[i];
    }
    for (i = 0; i < n; i++) {
        if ((i+1)%2==0) {
            f[i]=max(a[i]+get(i-2),g[i-1]);
        } else {
            f[i]=max(a[i]+get(i-2),f[i-1]);
        }
    }
    printf("%lld\n", f[n-1]);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(ll i = 0, i##_len = (n); i < i##_len; ++i)
#define rep2(i, x, n) for(ll i = x, i##_len = (n); i < i##_len; ++i)
#define all(n) begin(n), end(n)
using ll = long long;
using P = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vs = vector<string>;
using vc = vector<char>;
using vb = vector<bool>;
using vd = vector<double>;
vi dir = {-1, 0, 1, 0, -1, -1, 1, 1, -1};

int main() {
  ll n;
  cin >> n;
  vl a(n);
  rep(i, n) cin >> a[i];
  ll m = n % 2 + 1;
  ll dp[n + 1][m + 1][2] = {};
  rep(i, n + 1) rep(j, m + 1) rep(k, 2) dp[i][j][k] = -1e18;
  dp[0][0][0] = 0;
  rep(i, n) rep(j, m + 1) rep(k, 2) {
    if(k == 1)
      dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][k]);
    else {
      if(j != 0 || i != n - 1)
        dp[i + 1][j][1] = max(dp[i + 1][j][1], dp[i][j][k] + a[i]);
      if(j < m) dp[i + 1][j + 1][0] = max(dp[i + 1][j + 1][0], dp[i][j][k]);
    }
  }
  ll ans = -1e18;
  rep(j, m + 1) rep(k, 2) ans = max(ans, dp[n][j][k]);
  cout << ans << endl;
}


#include <iostream>
#include <string>
#include <sstream>

int partition(int* arr, int n)
{
    const int x = arr[n - 1];   //pivot value
    int i = 0;  //increment if swaped
    int j = 0;  //increment every loop
    for (; j < n; ++j) {   //scan start to end
        if (arr[j] <= x) {
            std::swap(arr[i], arr[j]);
            ++i;
        }
    }
    return i - 1;
}

void print(int const* arr, const int n, int q, int i)
{
    if (i == n - 1 ) {
        std::cout << arr[i] << std::endl;
        return;
    }

    if (i == q) {
        std::cout << "[" << arr[i] << "] ";
    }
    else {
        std::cout << arr[i] << " ";
    }

    return print(arr, n, q, i + 1);
}

void print(int const* arr, const int n, int q)
{
    print(arr, n, q, 0);
    return;
}

int main()
{
    int n;
    {
        std::string buf;
        std::getline(std::cin, buf);
        n = std::stoi(buf);
    }

    int arr[100000];
    {
        std::string buf;
        std::getline(std::cin, buf);
        std::stringstream stream;
        stream << buf;
        for (int i = 0; std::getline(stream, buf, ' '); ++i) {
            arr[i] = std::stoi(buf);
        }
    }

    int q = partition(arr, n);
    print(arr, n, q);

    return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>

using namespace std;
int A[100001];
int n;
int partition(){
	int i = -1;
	for (int j = 0; j < n - 1; ++j) if (A[j] <= A[n-1]) swap(A[++i], A[j]);
	swap(A[i + 1], A[n-1]);
	return i + 1;
}
int main(){
	scanf("%d",&n);
	for (int i = 0; i < n; ++i) scanf("%d",&A[i]);
	int pivot = partition();
	for (int i = 0; i < n; ++i){
		if (i != 0) cout << ' ';
		if (i == pivot){
			cout << '[' << A[i] << ']';
		}
		else cout << A[i];
	}
	cout << '\n';
}


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

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

typedef long long ll;
typedef array<int, 3> tri;
typedef long double ld;

template <class T> istream& operator>>(istream& I, vector<T>& v) {for (T &e: v) I >> e; return I;}
template <class T> ostream& operator<<(ostream &O, const vector<T>& v) {for (const T &e: v) O << e << ' '; return O;}

const int MOD = 1E9 + 7;
void _main() {
        int n, m; cin >> n >> m;
        vector<int> x(n), y(m); cin >> x >> y;

        auto solve = [](vector<int> a) {
                ll ans = 0, pre = 0;
                int n = sz(a);
                for (int i = 0; i < n; i++) {
                        ans += (ll) i * a[i] - (ll)(n - i - 1) * a[i];
                        ans += MOD;
                        ans %= MOD;
                }

                return ans;
        };

        cout << solve(x) * solve(y) % MOD;
}

signed main() {
        ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//        freopen("input.txt", "r", stdin);
        int _t = 1;
//        cin >> _t;
        while (_t--) _main();
        return 0;
}

#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define vll vector<ll>

using namespace std;

const ll N = 4e5+100;
const ll MOD = 1e9+7;
string s,t;
ll tree[N];

void build(ll node,ll l,ll r)
{
	if(l==r)
	{
		tree[node] = (s[l-1] == t[r-1]);
	}
	else
	{
		ll mid = (l + r) >> 1LL;
		build(node*2,l,mid);
		build(2*node+1,mid+1,r);
		tree[node] = tree[node*2] + tree[node*2+1];
	}
}

ll query(ll node,ll st,ll en,ll l,ll r)
{
	if(r < st || l> en) return 0;
	if(st >= l && en <= r) return tree[node];
	ll mid = (st + en)/2;
	ll p1 = query(node*2,st,mid,l,r);
	ll p2 = query(node*2+1,mid+1,en,l,r);
	return p1 + p2;
}

ll pre[N];
ll pr2[N];
int main()
{
	ll n,m;
	cin >> n >>m;
	ll a[n+1],b[m+1];

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

	ll co = 0,co2 = 0;

	for(int i =0;i<(n-1);i++)
	{
		ll x = i+1;
		co = co + ((a[i+1]- a[i]) * (x) * (n-x));
		if(co < MOD) co+=MOD;
		co%=MOD;
	}

	for(int i =0;i<(m-1);i++)
	{
		ll x = i+1;
		co2 = co2 + ((b[i+1]- b[i]) * (x) * (m-x));
		if(co2 < MOD) co2+=MOD;
		co2%=MOD;
	}

	 cout << (co*co2) %MOD << endl;

	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<bitset>
#include<deque>
#include<functional>
#include<iterator>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<utility>
using namespace std;
typedef long long ll;
#define a first
#define b second
#define sz(x) (ll)((x).size())
#define pb push_back
#define mp make_pair
#define bg begin()
#define ed end()
#define all(x) (x).bg,(x).ed
#define rep(i,n) for(ll i=0;i<(n);i++)
#define rep1(i,n) for(ll i=1;i<=(n);i++)
#define rrep(i,n) for(ll i=(n)-1;i>=0;i--)
#define rrep1(i,n) for(ll i=(n);i>=1;i--)
#define FOR(i,a,b) for(ll i=(a);i<(b);i++)
const ll MOD=1000000007;
const ll INF=1000000000000000;
template<class T> inline bool chmin(T& a, T b){if(a>b){a=b;return true;}return false;}
template<class T> inline bool chmax(T& a, T b){if(a<b){a=b;return true;}return false;}
ll maxx(ll x,ll y,ll z){return max(max(x,y),z);}
ll minn(ll x,ll y,ll z){return min(min(x,y),z);}
ll gcd(ll x,ll y){if(x%y==0) return y;else return gcd(y,x%y);}
ll lcm(ll x,ll y){return x*(y/gcd(x,y));}
ll digsz(ll x){if(x==0) return 1;else{ll ans=0;while(x){x/=10;ans++;}return ans;}}
ll digsum(ll x){ll sum=0;while(x){sum+=x%10;x/=10;}return sum;}
vector<ll> pw2(62,1);vector<ll> pw10(19,1);

int main(){
    {rep1(i,61) pw2[i]=2*pw2[i-1];}
    {rep1(i,18) pw10[i]=10*pw10[i-1];}

    ll N; cin>>N;
    ll ans=0;
    string x; cin>>x;
    string s="i";
    s+=x;
    ll Bcnt=0;
    rep1(i,N){
        if(s[i]=='B') Bcnt++;
    }
    rep1(R,N)rep1(G,N){
        if(s[R]=='R' && s[G]=='G'){ //B探す
            ll ans1,ans2,ans3,tmp=Bcnt;
            if(abs(R-G)%2==0){
                ans1=(R+G)/2;
                if(s[ans1]=='B') tmp--;
            }
            ans2=2*R-G;
            if(1<=ans2 && ans2<=N && s[ans2]=='B') tmp--;
            ans3=2*G-R;
            if(1<=ans3 && ans3<=N && s[ans3]=='B') tmp--;

            ans+=tmp;
        }
    }
    cout<<ans<<endl;
}

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

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

typedef long long ll;

#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--)
//定数
#define INF 1000000000000 //10^12:極めて大きい値,∞
//略記
#define PB push_back //vectorヘの挿入
#define MP make_pair //pairのコンストラクタ
#define F first //pairの一つ目の要素
#define S second //pairの二つ目の要素

int main(){
    int N;
    string S;
    cin>>N>>S;
    vector<int> v(3);
    rep(i,N) v[S[i]%3]++;
    ll ans=(ll)v[0]*v[1]*v[2];
    ll sub=0;
    rep(i,N){
        for(int j=i+1;j<N;j++){
            if(S[i]==S[j]) continue;
            int k=2*j-i;
            if(k>=N) continue;
            if(S[i]==S[k] || S[j]==S[k]) continue;
            sub++;
        }
    }
    ans-=sub;
    cout<<ans<<endl;
    return 0;
}


#include<bits/stdc++.h>
#define re register
#define inc(i,j,k) for(re int i=j;i<=k;i++)
using namespace std;
const int N=105;
inline int read(){
	int x=0;
	char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while('0'<=ch&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x;
}
int n,m,a[N],pos[N],cnt;
int main(){
	n=read(),m=read();
	inc(i,1,m) a[i]=read();
	inc(i,1,m) if(a[i]&1) pos[++cnt]=i;
	if(cnt>2) return puts("Impossible"),0;
	if(pos[1]) swap(a[1],a[pos[1]]);
	if(pos[2]) swap(a[m],a[pos[2]]);
	if(m==1&&a[1]==1) return printf("1\n1\n1"),0;
	inc(i,1,m) printf("%d ",a[i]);
	puts("");
	if(m==1) return printf("2\n1 %d",n-1),0;
	a[1]++,a[m]--;
	if(!a[m]) m--;
	printf("%d\n",m);
	inc(i,1,m) printf("%d ",a[i]);
}

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using ll = long long;

template <typename T>
T min(T a, T b){
  return (a < b) ? a : b;
}

template <typename T>
class SegTree{
  static const int MAXN = 100010;
  T INF;
  int n;
  T A[MAXN*4];
  T time[MAXN*4];
  public:
  SegTree(int size, T INF): INF(INF){
    n = 1;
    while(n < size){
      n *= 2;
    }
    n *= 2;
    for(int i = 0; i < MAXN*4; i++) A[i] = INF;
    for(int i = 0; i < MAXN*4; i++) time[i] = 0;
  }

  void update(int a, int b, T v, T t){
    return _update(a, b, 0, 0, n, v, t);
  }

  void _update(int a, int b, int k, int l, int r, T v, T t){
    if(a >= r || b <= l){
      return;
    }
    if(l >= a && r <= b){
      A[k] = v;
      time[k] = t;
      return;
    }
    _update(a, b, 2*k + 1, l, (l+r)/2, v, t);
    _update(a, b, 2*k + 2, (l+r)/2, r, v, t);
  }

  T query(int _idx){
    int offset = n - 1;
    int idx = _idx + offset;
    T t = 0;
    T ans = INF;
    while(idx > 0){
      if(time[idx] >= t){
        ans = A[idx];
        t = time[idx];
      }
      idx = (idx-1)/2;
    }
    return ans;
  }
};

int main(void){
  int n, q; cin >> n >> q;
  SegTree<int> rmq(n, 0x7FFFFFFF);
  for(int loop = 0; loop < q; loop++){
    int com;
    cin >> com;
    if(com == 0){
      int x, y, v; cin >> x >> y >> v;
      rmq.update(x, y+1, v, loop+1);
    }else{
      int i; cin >> i;
      cout << rmq.query(i) << endl;
    }
  }
}


// I SELL YOU...!
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<queue>
#include<chrono>
#include<iomanip>
#include<map>
#include<set>
using namespace std;
using ll = long long;
using P = pair<ll,ll>;
void init_io(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << setprecision(10);
}
signed main(){
  init_io();
  ll n;
  string s;
  cin >> n >> s;
  vector<ll> a(n,0);
  for(int x=0;x<2;x++){
    for(int y=0;y<2;y++){
      a[0] = x;
      a[1] = y;
      for(int i=1;i<n-1;i++){
        //sheep
        if(a[i]==0){
          if(s[i]=='o'){
            a[i+1] = a[i-1];
          }else{
            a[i+1] = !a[i-1];
          }
        //wolf
        }else{
          if(s[i]=='o'){
            a[i+1] = !a[i-1];
          }else{
            a[i+1] = a[i-1];
          }
        }
      }
      bool is_ans=true;
      if(a[0]==0){
        if(s[0]=='o'&&a[1]!=a[n-1]){
          is_ans = false;
        }else if(s[0]=='x'&&a[1]==a[n-1]){
          is_ans = false;
        }
      }else{
        if(s[0]=='o'&&a[1]==a[n-1]){
          is_ans = false;
        }else if(s[0]=='x'&&a[1]!=a[n-1]){
          is_ans = false;
        }
      }
      if(a[n-1]==0){
        if(s[n-1]=='o'&&a[n-2]!=a[0]){
          is_ans = false;
        }else if(s[n-1]=='x'&&a[n-2]==a[0]){
          is_ans = false;
        }
      }else{
        if(s[n-1]=='o'&&a[n-2]==a[0]){
          is_ans = false;
        }else if(s[n-1]=='x'&&a[n-2]!=a[0]){
          is_ans = false;
        }
      }
      if(is_ans){
        for(int i=0;i<n;i++){
          if(a[i]==0) cout <<"S";
          else cout <<"W";
        }
        cout << endl;
        return 0;
      }
    }
  }
  cout << "-1\n";
}

#include <cstdio>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;

int main()
{
    string s;
    cin >> s;
    int n = s.size();

    int ret = 0;
    for(int i=0; i<n; ++i){
        int j = i;
        while(j < n && s[j] == 'O')
            ++ j;
        int m = j - i;

        if(i - m >= 0 && s.substr(i - m, m) == string(m, 'J')){
            if(s.substr(j, m) == string(m, 'I')){
                ret = max(ret, m);
            }
        }

        i = j;
    }

    cout << ret << endl;
    return 0;
}


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

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

    int n;

    cin >> n;

    set <int> s;

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

        cin >> temp;

        s.insert(temp);
    }

    if(s.size() == n)
    {
        cout << "YES";
    }

    else
    {
        cout << "NO";
    }
}

#include<iostream>
using namespace std;

int main(){

	int n, num[10000];
	int max = -1000000, min = 1000000;
	long long sum = 0;

	cin >> n;

	for(int i = 0; i < n; i++){
		cin >> num[i];

		if(min > num[i]) min = num[i];
		if(max < num[i]) max = num[i];
		sum = sum + num[i];
	}

	cout << min << " " << max << " " << sum << endl;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
#define rep(i,n) for (int i=0; i<(n); i++)
#define reps(i,s,n) for (int i=(s); i<(n); i++)
#define rep1(i,n) for (int i=1; i<=(n); i++)
#define repr(i,s,n) for (int i=(s)-1; i>=(n); i--)
#define print(a) cout << (a) << endl
#define all(v) v.begin(), v.end()
#define rsort(v) sort(v.rbegin(), v.rend())

struct UnionFind {
  vector<int> par;
  UnionFind(int n) : par(n) { par.assign(n, -1); }

  int root(int a) {
    if (par[a] < 0)
      return a;
    return par[a] = root(par[a]);
  }
  int size(int a) { return -par[root(a)]; }
  void unite(int a, int b) {
    int ra = root(a), rb = root(b);
    if (ra == rb)
      return;
    if (par[a]>par[b])
      swap(a, b);
    par[ra] += par[rb];
    par[rb] = ra;
    return;
  }
  bool same(int a, int b) {
    int ra = root(a), rb = root(b);
    return ra == rb;
  }
};
UnionFind uft(100001);

struct edge {
  ll cost;
  int n1;
  int n2;
  bool operator<(const edge& right) const {
    return cost<=right.cost;
  }
};

int main() {
  int N;
  cin >> N;
  vector<pair<ll,int>> X(N),Y(N);
  rep(i,N) {
    ll x,y;
    cin >> x >> y;
    X[i] = {x,i};
    Y[i] = {y,i};
  }
  set<edge> S;
  sort(all(X));
  sort(all(Y));
  rep1(i,N-1) {
    S.insert({X[i].first-X[i-1].first, X[i].second, X[i-1].second});
    S.insert({Y[i].first-Y[i-1].first, Y[i].second, Y[i-1].second});
  }
  ll ans = 0;
  while (!S.empty()) {
    auto it = S.begin();
    S.erase(it);
    if (uft.same(it->n1,it->n2)) {
      continue;
    }
    uft.unite(it->n1,it->n2);
    ans += it->cost;
  }
  print(ans);
  return 0;
}

#include <bits/stdc++.h>
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for (ll i = (ll)(a); i < (ll)(b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define ll long long
#define lld long double
#define ALL(x) x.begin(), x.end()
using namespace std;

const double EPS = 1e-3;
const double PI = 3.1415926535897932384626433832795028841971;
const int IINF = 1 << 30;
const ll INF = 1ll << 60;
const ll MOD = 1e9 + 7;

int main()
{
    int n;
    cin >> n;
    vector<pair<ll, int>> x(n), y(n);
    rep(i, n)
    {
        x[i].second = i;
        cin >> x[i].first;
        y[i].second = i;
        cin >> y[i].first;
    }
    sort(ALL(x));
    sort(ALL(y));
    vector<int> xpos(n), ypos(n);
    rep(i, n)
    {
        xpos[x[i].second] = i;
        ypos[y[i].second] = i;
    }
    priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pque;
    pque.push({0, 0});
    ll ans = 0;
    vector<bool> used(n, false);
    while (!pque.empty())
    {
        //       cerr << pque.size() << endl;
        ll cost = pque.top().first;
        int idx = pque.top().second;
        pque.pop();
        if (used[idx])
        {
            continue;
        }
        //cerr << idx << " " << cost << endl;
        used[idx] = true;
        //cerr << xpos[idx] << endl;
        ans += cost;
        if (xpos[idx] > 0 && !used[x[xpos[idx] - 1].second])
        {
            pque.push({llabs(x[xpos[idx]].first - x[xpos[idx] - 1].first), x[xpos[idx] - 1].second});
        }
        if (ypos[idx] > 0 && !used[y[ypos[idx] - 1].second])
        {
            pque.push({llabs(y[ypos[idx]].first - y[ypos[idx] - 1].first), y[ypos[idx] - 1].second});
        }

        if (xpos[idx] + 1 < n && !used[x[xpos[idx] + 1].second])
        {
            pque.push({llabs(x[xpos[idx]].first - x[xpos[idx] + 1].first), x[xpos[idx] + 1].second});
        }
        if (ypos[idx] + 1 < n && !used[y[ypos[idx] + 1].second])
        {
            pque.push({llabs(y[ypos[idx]].first - y[ypos[idx] + 1].first), y[ypos[idx] + 1].second});
        }
    }
    cout << ans << endl;

    return 0;
}


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

bool is_squere(long N) {
        long r = (long) floor(sqrt(N));
        return (r * r) == N;
}

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

    for(int i = N; i > 0; i--) {
        if(is_squere(i)) {
            cout << i << endl;
            return 0;
        }
    }
}

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

int main() {
  int n;
  cin >> n;

  int i = 1;
  while(1) {
    if(i*i>n) break;
    i++;
  }
  cout << (i-1)*(i-1) << endl;
  return 0;
}


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

int is_prime(int n){
  if(n<2) return 0;
  else if(n==2) return 1;
  else if(n%2==0) return 0;

  double sqrtNum = sqrt(n);
    for (int i = 3; i <= sqrtNum; i += 2)
    {
        if (n % i == 0)
        {
            return 0;
        }
    }
    return 1;
}

int main(){
  int n;
  cin >> n;
  int cnt=0;
  int cal=11;
  vector<int> ans;
  while(cnt!=n){
    if(is_prime(cal)){
      if(cal%5==1){
        ans.push_back(cal);
        cnt++;
        //cout << cal << endl;
      }
    }

    cal++;
  }
  for(int i=0;i<n;++i){
    if(i!=n-1) cout << ans[i] << " ";
    else cout << ans[i] << endl;
  }

  return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <queue>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <fstream>
#include <stdio.h>
#include <complex>
#include <cstdint>
#include <tuple>
#include <regex>
#include <numeric>

#define M_PI       3.14159265358979323846

using namespace std;

//conversion
//------------------------------------------
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(); }

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;

//container util

//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define MOD 1000000007
#define SQ(x) ((x)*(x))

int main() {
	LL k;
	cin >> k;
	int n = 50;
	VLL ret(n);
	LL x = (k + 49) / 50 - 1;
	LL t = ((k + 49) / 50) * 50;
	REP(i, n) ret[i] = 50 + x - i;
	int loop = ((k + 49) / 50) * 50 - k;
	REP(i, loop) {
		REP(j, n) {
			ret[j]++;
		}
		ret[i] -= 51;
	}
	printf("%d\n", n);
	REP(i, n)printf("%lld ", ret[i]);
	printf("\n");
	return 0;
}


#include<stdio.h>
int max(int a,int b){return a>b?a:b;}
int main(){
	int i,j;
	int n;
	char c;
	int jc=0;
	int oc=0;
	int ic=0;
	int lev=0;
	int ans=0;
	scanf("%d",&n);
	while(scanf("%c",&c)!=EOF){
		switch(c){
		case 'J':
			if(jc==0){
				oc=0;
				ic=0;
				lev=0;
			}
			jc++;
			break;
		case 'O':
			if(oc==0){
				if(jc>0)lev=jc;
				if(ic>0)lev=0;
				jc=0;
				ic=0;
			}
			oc++;
			if(lev<oc){
				oc=0;
				lev=0;
			}
			break;
		case 'I':
			if(ic==0){
				if(lev>0)lev=oc;
				jc=0;
				oc=0;
			}
			ic++;
			if(ic>=lev)ans=max(ans,lev);
			break;
		}
	}
	printf("%d\n",ans);
}

#include<bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<char,int> P;

signed main(){
  string str;
  cin>>str;

  vector<P> A;
  int idx=0;
  while(idx<str.size()){
    char ch = str[idx];
    int cnt=0;
    while(str[idx] == ch) idx++,cnt++;
    A.push_back(P(ch,cnt));
  }

  int ans = 0;
  for(int i=1;i<(int)A.size() - 1;i++){
    if(A[i-1].first!='J' || A[i].first !='O' || A[i+1].first !='I')continue;
    int J = A[i-1].second;
    int O = A[i].second;
    int I = A[i+1].second;
    if(O<=I && O<=J) ans = max(ans,min(O,min(J,I)));
  }
  cout<<ans<<endl;

  return 0;
}


#pragma region header
#define _GLIBCXX_DEBUG
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define ts to_string
#define all(v) (v).begin(), (v).end()
#define resort(v) sort((v).rbegin(), (v).rend())
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define vs vector <string>
#define vvs vector <vector<string>>
#define pq  priority_queue<int>
#define smallpq  priority_queue<int, vector<int>, greater<int>>
using ll = long long;
using P = pair<int, int>;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
constexpr ll mod = 1e9 + 7;
constexpr ll inf = INT32_MAX / 2;
constexpr ll INF = LLONG_MAX / 2;
constexpr long double eps = DBL_EPSILON;
constexpr long double pi = 3.141592653589793238462643383279;
/* ----------------------end----------------------- */
/* --------------------テンプレート------------------ */
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
/* ----------------------end----------------------- */

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

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
using PLL = pair<ll, ll>;
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define repn(i,n) for(int i = 0; i <= (int)(n); i++)
#define srep(i,l,n) for(int i = l; i < (int)(n); i++)
#define srepn(i,l,n) for(int i = l; i <= (int)(n); i++)
#define drep(i,n) for(int i = (int)(n-1); i >= 0; i--)
#define drepn(i,n) for(int i = (int)(n); i >= 0; i--)
#define size(s) (int)s.size()
#define debug(var)  do{std::cout << #var << " : ";view(var);}while(0)
template<typename T> void view(T e){std::cout << e << std::endl;}
template<typename T> void view(const std::vector<T>& v){for(const auto& e : v){ std::cout << e << " "; } std::cout << std::endl;}
template<typename T> void view(const std::vector<std::vector<T> >& vv){ for(const auto& v : vv){ view(v); } }
template<typename T> inline istream& operator>>(istream &i, vector<T> &v) {rep(j, size(v)) i >> v[j]; return i;}
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
template<class T> T gcd(T a, T b) {if(b==0)return a; else return gcd(b,a%b);}
template<class T> T lcm(T a, T b) {return a/gcd(a,b)*b;}
template<class T = int> using V = vector<T>;
template<class T = int> using VV = vector<V<T>>;
bool isIn(int i, int j, int h, int w) {return i >= 0 && i < h && j >= 0 && j < w;}
void Yes(){cout << "Yes" << endl;}
void No(){cout << "No" << endl;}
void YES(){cout << "YES" << endl;}
void NO(){cout << "NO" << endl;}
void err() {cout << -1 << endl;}
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
#define ep emplace_back

const int MOD = 1000000007;
const int INF = 1e9;

#define PI acos(-1);
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int ddx[8] = {1,1,1,-1,-1,-1,0,0};
int ddy[8] = {0,1,-1,0,1,-1,1,-1};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, k;
    cin >> n >> k;
    V<> a(n);
    cin >> a;
    sort(rall(a));
    int ans = accumulate(a.begin(), a.begin() + k, 0);
    cout << ans << endl;
}


#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<iostream>
#define N 1100000
using namespace std;
char s[N],t[N];
int p[N],head,tail,n,f[N],ans;
int main()
{
	scanf("%d",&n);
	scanf("%s",s+1);
	scanf("%s",t+1);
	bool bo=1;
	for(int i=1;i<=n;i++) if(s[i]!=t[i]) {bo=0;break;}
	if(bo) {printf("0\n");return 0;}
	int j=n;
	for(int i=n;i>=1;i--)
	{
		j=min(j,i);
		while(j && s[j]!=t[i]) j--;
		if(j==0) {printf("-1\n");return 0;}
		f[i]=j;
	}
	head=1;tail=0;
	for(int i=n;i>=1;i--)
	{
		while(head<=tail && p[head]-(tail-head)>i) head++;
		if(f[i]!=f[i+1]) p[++tail]=f[i];
		ans=max(ans,tail-head+1);
	}
	printf("%d\n",ans);
	return 0;
}

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

#define ll long long

int dh[4] = {1, 0, -1, 0};
int dw[4] = {0, 1, 0 , -1};

const int INF = 100000;
int main() {

  int wcount = 0;
  char grid[100][100];
  int H, W;
  cin >> H >> W;
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      cin >> grid[i][j];
      if (grid[i][j] == '.') wcount++;
    }
  }

  int dp[100][100];
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      dp[i][j] = INF;
    }
  }

  dp[1][1] = 0;

  queue<pair<int,int>> que;
  pair<int, int> p = make_pair(1,1);
  que.push(p);

  while(que.size()) {
    pair<int, int> p = que.front();
    que.pop();

    int h = p.first, w = p.second;

    for (int i = 0; i < 4; i++) {
      int nh = h + dh[i], nw = w + dw[i];

      if (grid[nh][nw] == '.' && dp[nh][nw] == INF && nh >=1 && nh <= H && nw >= 1 && nw <= W) {
        dp[nh][nw] = dp[h][w] + 1;
        pair<int, int> np = make_pair(nh,nw);
        que.push(np);
      }
    }
  }

  if (dp[H][W] == INF) {
    cout << -1 << endl;
  } else {
    cout << wcount - dp[H][W] - 1 << endl;
  }

}


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

#define N 2
void InsertionSort(int* a, int n, int g);
void ShellSort(int* a, int n);

int a[1000005];
int cnt = 0;

int main(void){
    int n;
    cin >> n;

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

    ShellSort(a, n);

    cout << cnt << endl;

    for(int i=0; i<n; i++){
        printf("%d\n", a[i]);
    }

    return 0;
}

void InsertionSort(int* a, int n, int g){
    for(int i=g; i<n; i++){
        int v = a[i];
        int j = i - g;
        while(j >= 0 && a[j] > v){
            a[j+g] = a[j];
            j = j - g;
            cnt++;
        }
        a[j+g] = v;
    }
}

void ShellSort(int* a, int n){
    int g[100001];
    g[0] = 1;
    int i=0;
    while(g[i] <= n && i<100){
        g[i+1] = g[i] * 3 + 1;
        i++;
    }
    int m = i;
    for(int i=m-1; i>=0; i--){
        InsertionSort(a, n, g[i]);
    }

    cout << m << endl;
    for(int i=m-1; i>0; i--){
        printf("%d ", g[i]);
    }
    printf("%d\n", g[0]);
}

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

constexpr int n = 10;
int L[n+2],P[n];
int main(){
  string str;
  while(getline(cin,str)){
    string tmp;
    istringstream stream(str);
    for(int i=0;getline(stream,tmp,',');++i){
      L[i] = stod(tmp);
    }
    P[0] = L[0];
    for(int i=1;i<n;++i) P[i] = P[i-1] + L[i];
    int v1 = L[n],v2 = L[n+1];

    double p = (double)P[n-1]/(v1+v2)*v1;

    for(int i=0;i<n;++i){
      if(p<=P[i]){
        cout << i+1 << endl;
        break;
      }
    }

  }
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;

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

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

  deque<int> r;
  rep(i, n) {
    int idx = lower_bound(r.begin(), r.end(), a[i]) - r.begin();
    --idx;
    if (idx < 0) {
      r.push_front(a[i]);
    } else {
      r[idx] = a[i];
    }
  }

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

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

const int MAXN=500005;
const int NAX=1005;
const long long  MOD=(long long)(998244353);

Int N,M,K;
Int X,Y,Z;
Int H,W;

Int perform(Int x){
    return (x*(x+1))/2LL;
}
vector<Int> A;
vector<int> adj[MAXN];
using D=long double;

bool inRange(Int a,Int b){
    return a*b<=0;
}

long long C[NAX][NAX];
const D pi=3.14159265359;

long long ModExpo(long long x,unsigned long long y,long long M){
    Int ans=1;
    ans=(long long)ans;

    while(y>0){
        if(y&1) ans=((ans%M)*(x%M))%M;
        y>>=1LL;
        x=((x%M)*(x%M))%M;
    }
    return ans%M;
}
long long fac[MAXN];
void fillFac(){
    fac[0]=1;
    for(int i=1;i<MAXN;++i){
        fac[i]=((fac[i-1]%MOD)*(i%MOD))%MOD;
    }
}

long long ModInv(long long x){
    return ModExpo(x,MOD-2,MOD);
}

long long FermatLast(long long n,long long r){
    if(r>n) return 0;
    if(!r) return 1;
    return (fac[n] * ModInv(fac[r]) % MOD * ModInv(fac[n - r]) % MOD) % MOD;
}

Int performMod(Int x){
    Int y=((x%MOD)*((x+1)%MOD))%MOD;
    return (y*ModInv(2))%MOD;
}

Int madd(Int x,Int y){
    return (x+y)%MOD;
}

Int mmul(Int x,Int y){
    return ((x%MOD)*(y%MOD))%MOD;
}

bool isMSB(int bit,Int x){
    return (int)(floor(log2l(x)))==bit;
}
bool VIS[MAXN];
void dfs(int u){
    VIS[u]=true;
        for(auto &v:adj[u]){
            if(!VIS[v]){
                dfs(v);
            }
        }
}
int main()
{
    string S;cin>>S;
    vector<char> counts(26);
        for(auto x:S) ++counts[x-'a'];

        for(int i=0;i<26;++i){
            if(!counts[i]){
                cout<<char(i+'a');
                exit(0);
            }
        }
        cout<<"None\n";

}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int bubble(vector<int>::iterator, vector<int>::iterator);

int main() {
  int n;
  cin >> n;
  vector<int> nums;
  for(int i = 0; i < n; ++i) {
    int num;
    cin >> num;
    nums.push_back(num);
  }
  int count = 0;
  for(int i = 0; i < n - 1; ++i) {
    count += bubble(nums.begin(), nums.end() - i);
  }
  for(auto j = nums.begin(); j != nums.end() - 1; ++j) cout << *j << " ";
  cout << *(nums.end() - 1) << endl << count << endl;
  return 0;
}

int bubble(vector<int>::iterator begin, vector<int>::iterator end) {
  int count = 0;
  for(auto i = begin; i != (end - 1); ++i) {
    if(*i > *(i + 1)) {
      iter_swap(i, i + 1);
      ++count;
    }
  }
  return count;
}

#include <iostream>

using namespace std;

int bubblesort(int A[], int N) {
  int count = 0;
  int flag = 1;

  while (flag) {
    flag = 0;
    for (int i = N-1; i > 0; i--) {
      if (A[i] < A[i-1]) {
	swap(A[i], A[i-1]);
	flag = 1;
	count++;
      }
    }
  }

  for (int j = 0; j < N; j++) {
    if (j != N -1) cout << A[j] << " ";
    else cout <<A[j] << "\n";

  }

  cout << count << "\n";
}

int main() {

  int A[100];
  int N;

  cin >> N;

  for (int i=0; i < N; i++) {
    cin >> A[i];
  }

  bubblesort(A, N);
  return 0;
}


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

vector<P> G[1001][1001];
int dp[1001][1001];

vector<P> tp;

int dfs(int x,int y,int px=1000,int py=1000)
{
	if(dp[x][y]!=0)return dp[x][y];
	if(G[x][y].empty())return dp[x][y] = 1;
	for(auto i:G[x][y])
	{
		dp[x][y] = max(dp[x][y],dfs(i.first,i.second,x,y)+1);
	}
	return dp[x][y];
}

int main()
{
	int n;
	cin >> n;
	vector<vector<P>> input(n);
	map<P,int> h;//入次数
	for(int i = 0;i<n;i++)
	{
		for(int j = 0;j<n-1;j++)
		{
			int x=i;
			int y;
			cin >> y;
			y--;
			if(x>y)swap(x,y);
			input[i].emplace_back(x,y);

		}
	}
	for(int i = 0;i<n;i++)
	{
		for(int j =0;j<n-2;j++)
		{
			h[input[i][j+1]]++;
			G[input[i][j].first][input[i][j].second].emplace_back(input[i][j+1]);
		}
	}
	stack<P> S; //入次数がゼロの頂点
	for(int i = 0;i<n;i++)
	{
		for(int j = i+1;j<n;j++)
		{
			if(h[P(i,j)]==0)
			{
				S.emplace(i,j);
			}
		}
	}
	while(S.size())
	{
		auto now = S.top();S.pop();
		tp.push_back(now);
		for(auto i:G[now.first][now.second])
		{
			h[i]--;
			if(h[i]==0)S.emplace(i);
		}
	}
	if(tp.size()!=n*(n-1)/2)
	{
		cout << -1 << endl;
		return 0;
	}

	int ans = 0;
	for(int i = 0;i<n;i++)
	{
		for(int j = i+1;j<n;j++)
		{
			ans = max(ans,dfs(i,j));
		}
	}
	cout << ans << endl;
}

#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
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; }
typedef long long ll;
using namespace std;
int main(void){
    int n;cin>>n;
    vector<vector<int>> a(n,vector<int>(n));
    rep(i,n)rep(j,n-1){
        cin>>a[i][j];a[i][j]--;
    }
    vector<int> t(n,0);
    vector<bool> used(n,false);
    ll cou=0;
    queue<int> que1;
    rep(i,n) que1.push(i);
    while(true){
        cou++;
        //cout<<que1.size()<<endl;
        rep(i,n)used[i]=false;
        bool changed=false;
        queue<int> que2;
        while(que1.size()){
            int i=que1.front();que1.pop();
            if(used[i]||t[i]==n-1)continue;
            int b=a[i][t[i]];
            if(!used[b]&&a[b][t[b]]==i&&t[b]<n-1){
                used[i]=true;used[b]=true;changed=true;
                t[i]++;t[b]++;
                que2.push(i);que2.push(b);
            }
        }

        if(!changed){
            cout<<-1<<endl;
            return 0;
        }
        rep(i,n){
            if(t[i]!=n-1)changed=false;
        }
        if(changed){
            cout<<cou<<endl;
            return 0;
        }
        swap(que1,que2);
    }
}


#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
#include <fstream>
#include <utility>
#include <functional>
#include <time.h>
#include <stack>
#include <array>
#include <list>
#define popcount __builtin_popcount
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
const ll MOD=998244353;
ll powmod(ll a, ll k){
    ll ap=a, ans=1;
    while(k){
        if(k&1){
            ans*=ap;
            ans%=MOD;
        }
        ap=ap*ap;
        ap%=MOD;
        k>>=1;
    }
    return ans;
}
ll inv(ll a){
    return powmod(a, MOD-2);
}
ll dp[303][303][303];
int main()
{
    string s;
    int k;
    cin>>s>>k;
    s+='0';
    int cnt=0;
    vector<int> v;
    int l=0;
    for(int i=0; i<s.size(); i++){
        if(s[i]=='0'){
            v.push_back(cnt);
            cnt=0;
        }else{
            cnt++; l++;
        }
    }
    int m=v.size();
    dp[0][0][0]=1;
    for(int i=0; i<m; i++){
        for(int j=0; j<=l; j++){
            for(int t=0; t<=l; t++){
                if(dp[i][j][t]==0) continue;
                for(int u=max(0, v[i]-t); u<=min({l, l+v[i]-t, l+v[i]-j}); u++){
                    if(u<v[i]){
                        dp[i+1][j][t-(v[i]-u)]+=dp[i][j][t];
                        if(dp[i+1][j][t-(v[i]-u)]>=MOD) dp[i+1][j][t-(v[i]-u)]-=MOD;
                    }else{
                        dp[i+1][j+u-v[i]][t+u-v[i]]+=dp[i][j][t];
                        if(dp[i+1][j+u-v[i]][t+u-v[i]]>=MOD) dp[i+1][j+u-v[i]][t+u-v[i]]-=MOD;
                    }
                }
            }
        }
    }
    ll ans=0;
    for(int i=0; i<=min(l, k); i++){
        (ans+=dp[m][i][0])%=MOD;
    }
    cout<<ans<<endl;
    return 0;
}

#include<cstdio>
#include<utility>
#include<algorithm>
#include<vector>
#include<queue>
#define MAX_N 262144
#define INF 1000000000000000
typedef long long ll;
using namespace std;

int used[MAX_N];
ll n,d,a[MAX_N],ans=0,two[20];
pair<ll,ll> p[MAX_N],t[2*MAX_N][2];
vector<pair<ll,ll> > g[MAX_N];
void init(){
    for(ll i=0;i<2*MAX_N;i++){
        t[i][0]=t[i][1]=make_pair(INF,i);
    }
    two[0]=1;
    for(int i=1;i<20;i++){
        two[i]=two[i-1]*2;
    }
}
void change(ll i){
    ll y=p[i].second+MAX_N;
    t[y][0].first=d*(y-MAX_N)+p[i].first;
    t[y][1].first=d*(n-1-y+MAX_N)+p[i].first;
    y/=2;
    while(y>0){
        t[y][0]=min(t[2*y][0],t[2*y+1][0]);
        t[y][1]=min(t[2*y][1],t[2*y+1][1]);
        y/=2;
    }
}
pair<ll,ll> smq(ll l,ll r,int y){
    ll cnt=1,x=l;
    if(l==r){
        return t[l][y];
    }
    while(x>0){
        if(x/2*two[cnt]==l&&(x/2+1LL)*two[cnt]-(1LL)==r){
            return t[x/2][y];
        }
        else if(x/2*two[cnt]<l||(x/2+1LL)*two[cnt]-(1LL)>r){
            return min(t[x][y],smq((x+1LL)*two[cnt-1],r,y));
        }
        x/=2;
        cnt++;
    }
    return t[x][y];
}
int main(){
    pair<ll,ll> x;
    priority_queue<pair<ll,ll> ,vector<pair<ll,ll>>, greater<pair<ll,ll>>> q;
    scanf("%lld %lld",&n,&d);
    for(ll i=0;i<n;i++){
        scanf("%lld",&a[i]);
        p[i]=make_pair(a[i],i);
    }
    init();
    sort(p,p+n);
    change(0);
    for(ll i=1;i<n;i++){
        x=smq(p[i].second+MAX_N,n-1+MAX_N,0);
        if(x.first<INF){
            g[p[i].second].push_back(make_pair(x.first-d*p[i].second+p[i].first,x.second-MAX_N));
            g[x.second-MAX_N].push_back(make_pair(x.first-d*p[i].second+p[i].first,p[i].second));
        }
        x=smq(MAX_N,p[i].second+MAX_N,1);
        if(x.first<INF){
            g[p[i].second].push_back(make_pair(x.first-d*(n-1-p[i].second)+p[i].first,x.second-MAX_N));
            g[x.second-MAX_N].push_back(make_pair(x.first-d*(n-1-p[i].second)+p[i].first,p[i].second));
        }
        change(i);
    }
    used[p[n-1].second]=1;
    for(int i=0;i<g[p[n-1].second].size();i++){
        q.push(g[p[n-1].second][i]);
    }
    while(!q.empty()){
        x=q.top();
        q.pop();
        if(used[x.second]==0){
            ans+=x.first;
            for(int i=0;i<g[x.second].size();i++){
                q.push(g[x.second][i]);
            }
            used[x.second]=1;
        }
    }
    printf("%lld\n",ans);
}


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <map>
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
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; }

#define MOD 998244353

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

class mint{
    typedef long long ll;
public:
    mint(ll a){
        _val = a%_mod;
    }
    mint(){
        _val=0;
    }
    explicit operator ll() {return _val;}
    ll _val;
    static const ll _mod = MOD;
};

mint operator*(mint mi, mint i){
    return mint(mi._val * i._val);
}
mint operator+(mint mi, mint i){
    return mint(mi._val + i._val);
}
mint operator/(mint mi, mint i){
    ll div = modpow(i._val,mi._mod-2,mi._mod);
    return mint(mi._val*div);
}

int main(){
    /*
    mint a(8960);
    mint b = a+3;
    cout << b._val << endl;
    b=a+6;
    cout << b._val << endl;
    b=a*5;
    cout << b._val <<endl;
    b=7*a;
    cout << b._val <<endl;
    b=a/2/1;
    cout << (ll)b<<endl;
    */

    ll n,m,k;
    cin >> n >> m >> k;
    vector<mint> kj(n), MM(n);
    kj[0] = mint(1);
    MM[0] = mint(1);
    rep(i,n-1){
        kj[i+1] = kj[i] * (i+1);
        MM[i+1] = MM[i] * (m-1);
        //cout << i+1 << " kj[i+1]: "<< kj[i+1]._val <<" MM[i+1]: "<< MM[i+1]._val<<endl;
    }

    mint sum(0);
    rep(i,k+1){
        mint tmp;
        tmp= tmp+kj[n-1]*m*MM[n-1-i];
        tmp= tmp/kj[n-1-i]/kj[i];
        sum = sum+tmp;
    }
    cout<<sum._val<<endl;

    return 0;
}

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

int c[100][100];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, t;
    int M[101];
    cin>>n;
    cin>>M[0]>>M[1];
    for(int i=2; i<=n; i++) {
        cin>>t>>M[i];
    }
    for(int l=1; l<n; l++) {
        for(int i=0; i+l<n; i++) {
            int cost=numeric_limits<int>::max();
            for(int j=i+1; j<=i+l; j++) {
                cost=min(cost, c[i][j-1]+M[i]*M[j]*M[i+l+1]+c[j][i+l]);
            }
            c[i][i+l]=cost;
        }
    }
    cout<<c[0][n-1]<<'\n';
}


#include <bits/stdc++.h>
using namespace std;
int main(){
  int m;
  cin >> m;
  vector<int> nodes;
  vector<pair<int, int>> child;
  int n = 0;
  for (int i = 0; i < m; i++){
    string q;
    cin >> q;
    if (q == "insert"){
      int k;
      cin >> k;
      if (n != 0){
        int v = 0;
        while (1){
          if (k < nodes[v]){
            if (child[v].first != -1){
              v = child[v].first;
            } else {
              child[v].first = nodes.size();
              break;
            }
          } else {
            if (child[v].second != -1){
              v = child[v].second;
            } else {
              child[v].second = nodes.size();
              break;
            }
          }
        }
      }
      nodes.push_back(k);
      child.push_back(make_pair(-1, -1));
      n++;
    }
    if (q == "find"){
      int k;
      cin >> k;
      if (n == 0){
        cout << "no" << endl;
      } else {
        int v = 0;
        while (1){
          if (k < nodes[v]){
            if (child[v].first == -1){
              cout << "no" << endl;
              break;
            } else {
              v = child[v].first;
            }
          } else if (k > nodes[v]){
            if (child[v].second == -1){
              cout << "no" << endl;
              break;
            } else {
              v = child[v].second;
            }
          } else {
            cout << "yes" << endl;
            break;
          }
        }
      }
    }
    if (q == "delete"){
      int k;
      cin >> k;
      int v = 0;
      int u;
      while (1){
        if (k < nodes[v]){
          u = v;
          v = child[v].first;
        } else if (k > nodes[v]){
          u = v;
          v = child[v].second;
        } else {
          break;
        }
      }
      if (child[v].first != -1 && child[v].second != -1){
        u = v;
        int w = child[v].second;
        while (child[w].first != -1 || child[w].second != -1){
          u = w;
          if (child[w].first != -1){
            w = child[w].first;
          } else {
            w = child[w].second;
          }
        }
        swap(nodes[v], nodes[w]);
        v = w;
      }
      if (child[v].first != -1 && child[v].second == -1){
        int w = child[v].first;
        nodes[v] = nodes[w];
        child[v].first = child[w].first;
        child[v].second = child[w].second;
      } else if (child[v].second != -1 && child[v].first == -1){
        int w = child[v].second;
        nodes[v] = nodes[w];
        child[v].first = child[w].first;
        child[v].second = child[w].second;
      } else {
        if (child[u].first == v){
          child[u].first = -1;
        } else {
          child[u].second = -1;
        }
      }
      n--;
    }
    if (q == "print"){
      //Inorder
      if (n != 0){
        stack<int> S;
        vector<int> t(nodes.size(), 0);
        S.push(0);
        while (!S.empty()){
          int v = S.top();
          S.pop();
          if (t[v] == 1){
            cout << ' ' << nodes[v];
          }
          if (t[v] == 0){
            S.push(v);
            if (child[v].second != -1){
              S.push(child[v].second);
            }
            S.push(v);
            if (child[v].first != -1){
              S.push(child[v].first);
            }
          }
          t[v]++;
        }
      }
      cout << endl;
      //Preorder
      if (n != 0){
        stack<int> S;
        vector<int> t(nodes.size(), 0);
        S.push(0);
        while (!S.empty()){
          int v = S.top();
          S.pop();
          if (t[v] == 0){
            cout << ' ' << nodes[v];
          }
          if (t[v] == 0){
            S.push(v);
            if (child[v].second != -1){
              S.push(child[v].second);
            }
            S.push(v);
            if (child[v].first != -1){
              S.push(child[v].first);
            }
          }
          t[v]++;
        }
      }
      cout << endl;
    }
  }
}

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

typedef struct node{
	int key;
	struct node *parent;
	struct node *left;
	struct node *right;
} Node, Tree;

void insert(Tree **T, int key)
{
	Node *pre = NULL;
	Node *curr = *T;
	Node *newNode = NULL;

	newNode = (Node*)malloc(sizeof(Node));
	newNode->key = key;
	newNode->left = NULL;
	newNode->right = NULL;

	while (curr != NULL) {
		pre = curr;
		if (key > curr->key) {
			curr = curr->right;
		} else {
			curr = curr->left;
		}
	}

	newNode->parent = pre;

	//如果根结点存在，则pre一定不为空，反之pre为空
	if (pre == NULL) {
		*T = newNode;
	} else {
		if (key > pre->key) {
			pre->right = newNode;
		} else {
			pre->left = newNode;
		}
	}
}

void Inorder(Tree *T)
{
	if (T == NULL)
		return;

	Inorder(T->left);
	cout << " " << T->key;
	Inorder(T->right);
}

void Preorder(Tree *T)
{
	if (T == NULL)
		return;

	cout << " " << T->key;
	Preorder(T->left);
	Preorder(T->right);
}

bool find(Tree *T, int key)
{
	Node *curr = T;
	if (T == NULL)
		return false;

	while (curr != NULL) {
		if (key == curr->key)
			return true;
		else if (key > curr->key) {
			curr = curr->right;
		} else {
			curr = curr->left;
		}
	}

	return false;
}

Node *minNode(Node *N)
{
	Node *pre = NULL;
	Node *curr = N;

	while (curr != NULL) {
		pre = curr;
		curr = curr->left;
	}

	return pre;
}

bool deleteNode(Tree **T, int key)
{
	Node *pre = NULL;
	Node *curr = *T;
	Node *nextNode = NULL;
	Node *p = NULL;

	if (key == (*T)->key) {
		p = *T;
		if ((*T)->left == NULL && (*T)->right == NULL) {
			(*T) = NULL;
			free(p);
		} else if ((*T)->left == NULL) {
			(*T) = (*T)->right;
			free(p);
		} else if ((*T)->right == NULL) {
			(*T) = (*T)->left;
			free(p);
		} else {
			p = minNode((*T)->right);
			(*T)->key = p->key;
			if (p->right == NULL) {
				if (p->parent->left == p) {
					p->parent->left = NULL;
				} else {
					p->parent->right = NULL;
				}
			} else {
				(*T)->right = p->right;
				p->right->parent = (*T);
			}
			free(p);
		}

		return true;
	} else {
		while (curr != NULL) {
			if (key == curr->key) {
				if (curr->left == NULL && curr->right == NULL) {
					if (curr->parent->left == curr) {
						curr->parent->left = NULL;
					} else {
						curr->parent->right = NULL;
					}
					free(curr);
				} else if (curr->left == NULL) {

					if (curr->parent->left == curr) {
						curr->parent->left = curr->right;
					} else {
						curr->parent->right = curr->right;
					}
					curr->right->parent = curr->parent;
					free(curr);
				} else if (curr->right == NULL) {

					if (curr->parent->left == curr) {
						curr->parent->left = curr->left;
					} else {
						curr->parent->right = curr->left;
					}
					curr->left->parent = curr->parent;
					free(curr);
				} else {
					p = minNode(curr->right);
					curr->key = p->key;
					if (p->right == NULL) {
						if (p->parent->left == p) {
							p->parent->left = NULL;
						} else {
							p->parent->right = NULL;
						}
					} else {
						if (curr->left == p) {
							curr->left = p->right;
						} else {
							curr->right = p->right;
						}
						p->right->parent = curr;
					}
					free(p);
				}

				return true;
			} else if (key > curr->key) {
				curr = curr->right;
			} else {
				curr = curr->left;
			}
		}
	}

	return false;
}

void print(Tree *T)
{
	Inorder(T);
	cout << '\n';
	Preorder(T);
	cout << '\n';
}

int main(void)
{
	Tree *T = NULL;
	int n;
	int key;
	string cmd;

	//freopen("out.txt", "w", stdout);

	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> cmd;
		if (cmd == "insert") {
			cin >> key;
			insert(&T, key);
			//print(T);
		} else if (cmd == "print"){
			print(T);
		} else if (cmd == "find") {
			cin >> key;
			if (find(T, key) == true) {
				cout << "yes\n";
			} else {
				cout << "no\n";
			}
		} else if (cmd == "delete") {
			cin >> key;
			deleteNode(&T, key);
		}
	}

	return 0;
}


#include<iostream>
using namespace std;

string rep(string s,int a,int b,string p);
string rev(string s,int a,int b);
void pri(string s,int a,int b);

int main(){
        string code,k,p;
        int n,a,b;
        string haki;
        getline(cin,code);
        cin >> n;
        getline(cin, haki);
        for(int i = 0; i < n; i++){
                cin >> k;
                if(k == "replace"){
                        cin >> a >> b >> p;
                        code = rep(code ,a,b,p);
                }else if(k == "reverse"){
                        cin >> a >> b;
                        code =rev(code , a,b);
                }else if(k == "print"){
                        cin >> a >> b;
                        pri(code, a,b);
                }
                getline(cin,haki);
        }
}

string rep(string s,int a, int b, string p){
        for(int i = a; i <=b; i++){
                s[i] = p[i-a];
        }
        return s;
}string rev(string s, int a, int b){
        string p = s;
        for(int i = a; i <= b; i++){
                s[i] = p[b-i+a];
        }
        return s;
}
void pri(string s, int a, int b){
        for(int i = a; i <= b;i++){
                cout <<s[i];
        }
        cout << endl;
}

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

int main(){
	string str, trans, s;
	int q, a, b;

	cin>>str;
	cin>>q;

	for(int i=0;i<q;i++){
		cin>>trans>>a>>b;
		string left = str.substr(0, a);
		string right = str.substr(b+1, str.length()-b-1);

		if(trans == "print"){
			s = str.substr(a, b-a+1);
			cout<<s<<endl;
		}else if(trans == "reverse"){
			s = str.substr(a, b-a+1);
			str = left;
			for(int j=s.length()-1;j>=0;j--){
				str += s[j];
			}
			str += right;
		}else if(trans == "replace"){
			cin>>s;
			str = left + s + right;
		}
	}

	return 0;
}


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

#define ALL(v) v.begin(), v.end()
#define V vector
#define P pair
using ll = long long;
using ld = long double;
const int MOD = 1e9+7;
const ll INF = 1LL << 60;

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

    if(s == "hi" || s == "hihi" || s == "hihihi" || s == "hihihihi" || s == "hihihihihi") cout << "Yes" << endl;
    else cout << "No" << endl;

    return 0;
}

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

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

    bool ok = true;
    if (S.size() % 2 == 1) ok = false;
    for (int i = 0; i < S.size() / 2; i += 2) {
        if (S.substr(i, 2) != "hi") {
            ok = false;
        }
    }

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


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

int val=1,n;
double k;
int main (){
    cin>>n>>k;
    int z=k;
    while(double(k)/2>1){
        val++;
        k/=2;
    }

  if(n>=val){
       cout<<pow(2,val)+z*(n-val);
    }

    else{
        cout<<pow(2,n);
    }
}

#include <bits/stdc++.h>
using namespace std;
int main()
  {int N, K, n{1}; cin >> N >> K;
  while (N--) n += min(n, K);
  cout << n;}


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

int main() {
    int N;
    cin >> N;
    vector<pair<int,int> > team(N);
    for (int i = 0; i < N; i++) {
        team[i].second = i + 1;
    }

    for (int i = 0; i < N * (N - 1) / 2; i++) {
        int a, b, c, d;
        cin >> a >> b >> c >> d;
        if (c < d) team[b-1].first+=3;
        if (c > d) team[a-1].first+=3;
        if (c == d) {
            team[a-1].first++;
            team[b-1].first++;
        }
    }

    sort(team.begin(), team.end());
    reverse(team.begin(), team.end());

    vector<int> rank(N);
    rank[team[0].second-1] = 1;
    for (int i = 1, count = 1, r = 1; i < N; i++) {
        if (team[i].first == team[i-1].first) {
            rank[team[i].second-1] = r;
            count++;
        }
        else {
            r += count;
            rank[team[i].second-1] = r;
            count = 1;
        }
    }

    for (auto i : rank) cout << i << endl;

    return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>
#include <math.h>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <bitset>
#include <complex>
#include <unistd.h>
#include <cassert>
#include <cctype>
#include <random>
#define _USE_MATH_DEFINES
#define _GLIBCXX_DEBUG
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> plglg;
typedef pair<double, ll> pdlg;
typedef tuple<int, int, int> tiii;
typedef tuple<ll, ll, ll> tlglglg;
typedef tuple<double, double, double> tddd;
typedef complex<double> xy_t;
#define REP(i, x, y) for(ll i = x; i < y; i++)
#define PER(i, x, y) for(ll i = x; i > y; i--)
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
double pi = 3.141592653589793;
ll mod = 1000000007;
int intmax = 2147483647;
int intmin = -2147483648;
ll llmax = 9223372036854775807;
ll llmin = -9223372036854775807;
int iinf = intmax / 8;
ll inf = llmax / 8;
double eps = 1e-11;

ll multiply(ll x, ll y) {
    return (x % mod) * (y % mod) % mod;
}

ll modpower(ll x, ll y) {
    if (y == 0) {
        return 1;
    } else if (y == 1) {
        return x % mod;
    } else if (y % 2 == 0) {
        ll p = modpower(x, y / 2);
        return p * p % mod;
    } else {
        ll p = modpower (x, y / 2);
        return (p * p) % mod * (x % mod) % mod;
    }
}

ll divide(ll x, ll y) {
    return multiply(x, modpower(y, mod - 2));
}

ll frac[1000000];
ll invfrac[1000000];

void fracinvfrac(ll n) {
    frac[0] = 1;
    for (int i = 1; i <= n; i++) {
        frac[i] = multiply(frac[i - 1], i);
    }
    invfrac[n] = divide(1, frac[n]);
    for (int i = n - 1; i >= 0; i--) {
        invfrac[i] = multiply(invfrac[i + 1], i + 1);
    }
}

ll modcombi(ll x, ll y) {
    if (x < y || y < 0) {
        return 0;
    } else if (y == 0) {
        return 1;
    } else {
        return multiply(multiply(frac[x], invfrac[x - y]), invfrac[y]);
    }
}

ll dp[1010][1010];

ll mcb[1010][1010];

int main() {
    ll N, A, B, C, D;
    cin >> N >> A >> B >> C >> D;
    fracinvfrac(10000);
    REP(i, 0, 1010) {
        fill(dp[i], dp[i] + 1010, 0);
        REP(j, 0, 1010) {
            mcb[i][j] = modcombi(i, j);
        }
    }
    dp[0][0] = 1;
    REP(i, 1, N + 1) {
        REP(j, 0, N + 1) {
            dp[i][j] = dp[i - 1][j];
        }
        if (A <= i && i <= B) {
            REP(j, 0, N + 1) {
                ll combi = 1;
                if (j + i * C <= N) {
                    REP(k, 1, C) {
                        combi = multiply(combi, mcb[N - j - i * (k - 1)][i]);
                    }
                    REP(k, C, D + 1) {
                        if (j + i * k <= N) {
                            combi = multiply(combi, mcb[N - j - i * (k - 1)][i]);
                            dp[i][j + i * k] = (dp[i][j + i * k]
                                                + multiply(dp[i - 1][j], multiply(combi, invfrac[k]))) % mod;
                        }
                    }
                }
            }
        }
    }
    // REP(i, 0, N + 1) {
    //     REP(j, 0, N + 1) {
    //         cout << dp[i][j] << " ";
    //     }
    //     cout << endl;
    // }
    ll ans = dp[N][N];
    cout << ans << endl;
}

#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const ll mod = 1e9 + 7;
ll modpow(ll A, ll B) {
	ll kotae = 1;
	while (B > 0) {
		if (B & 1) kotae = kotae * A % mod;
		A = A * A % mod;
		B >>= 1;
	}
	return kotae;
}
const int IMAX = 1001;
ll fac[IMAX + 1], ifac[IMAX + 1];
int dp[1001];

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

	fac[0] = 1;
	rep1(i, IMAX) fac[i] = fac[i - 1] * i % mod;
	ifac[IMAX] = modpow(fac[IMAX], mod - 2);
	for (int i = IMAX; i > 0; i--) ifac[i - 1] = ifac[i] * i % mod;

	int N, A, B, C, D;
	scanf("%d %d %d %d %d", &N, &A, &B, &C, &D);
	dp[0] = fac[N];
	for (int i = A; i <= B; i++) {
		ll ic = modpow(ifac[i], C);
		for (int j = N - i * C; j >= 0; j--) {
			int tmp = dp[j] * ic % mod;
			int p = C;
			for (int k = j + i * C; k <= min(j + i * D, N); k += i) {
				dp[k] = (dp[k] + tmp * ifac[p++]) % mod;
				tmp = tmp * ifac[i] % mod;
			}
		}
	}
	printf("%lld", dp[N]);

	Would you please return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int N=101;
char s[N];
short g[N][N],f[N][N],v[N][N][N][N];
inline void upd(short &x,short y) {x=max(x,y);}
int main() {
    int n,m,x,y,ans=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++) {
	scanf("%s",s+1);
	for(int j=1;j<=m;j++) {
	    if(s[j]=='E') x=i,y=j;
	    int t=(s[j]=='o');
	    f[i][j]=f[i][j-1]+t,g[i][j]=g[i-1][j]+t;
	}
    }
    memset(v,-1,sizeof(v));
    v[0][0][0][0]=0;
    for(int i=0;i<x;i++)
	for(int j=0;x+j<=n;j++)
	    for(int p=0;p<y;p++)
		for(int q=0;y+q<=m;q++) {
		    int d=v[i][j][p][q];
		    if(d==-1) continue;
		    ans=max(ans,d);
		    if(j+1<x-i) upd(v[i+1][j][p][q],d+f[x-i-1][min(y+q,m-p)]-f[x-i-1][max(y-p,q+1)-1]);
		    if(x+j<n-i) upd(v[i][j+1][p][q],d+f[x+j+1][min(y+q,m-p)]-f[x+j+1][max(y-p,q+1)-1]);
		    if(q+1<y-p) upd(v[i][j][p+1][q],d+g[min(x+j,n-i)][y-p-1]-g[max(x-i,j+1)-1][y-p-1]);
		    if(y+q<m-p) upd(v[i][j][p][q+1],d+g[min(x+j,n-i)][y+q+1]-g[max(x-i,j+1)-1][y+q+1]);
		}
    cout<<ans;
    return 0;
}

/// {{{ Author: Wang, Yen-Jen
// include
#include <bits/stdc++.h>

// using
using namespace std;

// types
typedef long long ll;
typedef pair<int,int> pii;

// macro
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin() , (x).end()
#define REP(i , n) for(int i = 0; i < int(n); i++)
#define REP1(i , a , b) for(int i = a; i <= int(b); i++)
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define LC o<<1 , l , m
#define RC o<<1|1 , m + 1 , r
#define MS(x , v) memset(x , (v) , sizeof(x))

// input
inline bool SR(int &x) {
  return scanf("%d",&x) == 1;
}

inline bool SR(ll &x) {
  return scanf("%lld",&x) == 1;
}

inline bool SR(double &x) {
  return scanf("%lf",&x) == 1;
}

inline bool SR(char *s) {
  return scanf("%s",s) == 1;
}

inline bool RI() {
  return true;
}

template<typename I , typename... T> inline bool RI(I &x , T&... tail) {
  return SR(x) && RI(tail...);
}

// output
inline void SP(const int x) {
  printf("%d",x);
}

inline void SP(const ll x) {
  printf("%lld",x);
}

inline void SP(const double x) {
  printf("%.16lf",x);
}

inline void SP(const char *s) {
  printf("%s",s);
}

inline void PL() {
  puts("");
}

template<typename I , typename... T> inline void PL(const I x , const T... tail) {
  SP(x);
  if(sizeof...(tail)) putchar(' ');
  PL(tail...);
}

// debug
#define WangYenJen

#ifdef WangYenJen
template<typename I> void _DOING(const char *s , I&& x) {
  cerr << s << " = " << x << endl;
}

template<typename I , typename... T> void _DOING(const char *s , I&& x , T&&... tail) {
  int c = 0;
  while(*s != ',' || c != 0) {
    if(*s == '(' || *s == '[' || *s == '{') c++;
    if(*s == ')' || *s == ']' || *s == '}') c--;
    cerr << *s++;
  }
  cerr << " = " << x << " , ";
  _DOING(s + 1 , tail...);
}

#define DEBUG(...) \
do {\
  fprintf(stderr , "%s: Line %d - ",__PRETTY_FUNCTION__,__LINE__);\
  _DOING(#__VA_ARGS__ , __VA_ARGS__);\
} while(0);

#else
#define DEBUG(...)

#endif

// constant number
const int INF = 0x3f3f3f3f;
const ll INF64 = 0x3f3f3f3f3f3f3f3fll;

// random function
inline int RAND() {
  static int x = 880301;
  return (x = x * 0xdefaced + 1) % 0x7fffffff;
}
/// }}}

const int MAX_N = 100 + 3;

int n, m;
int sx, sy;
char str[MAX_N];
int sum[MAX_N][MAX_N];
short dp[MAX_N][MAX_N][MAX_N][MAX_N];

int get_sum(int x1, int y1, int x2, int y2) {
  if (x1 > x2 || y1 > y2) return 0;
  else return sum[x2][y2] - sum[x1][y2] - sum[x2][y1] + sum[x1][y1];
}

int main() {
  RI(n, m);
  REP1(i, 1, n) {
    SR(str + 1);
    REP1(j, 1, m) {
      if (str[j] == 'E') sx = i, sy = j;
      else if (str[j] == 'o') sum[i][j] = 1;
      sum[i][j] = sum[i][j] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
    }
  }
  int ans = 0;
  REP1(i, 0, sx - 1) {
    REP1(j, 0, sy - 1) {
      REP1(x, 0, n - sx) {
        REP1(y, 0, m - sy) {
          ans = max(ans, (int)dp[i][j][x][y]);
          int v = 0;
          if (i + x + 1 <= sx - 1) v = get_sum(sx - i - 2, max(sy - j - 1, y), sx - i - 1, min(sy + y, m - j));
          else v = 0;
          dp[i + 1][j][x][y] = max((int)dp[i + 1][j][x][y], dp[i][j][x][y] + v);
          if (i + x + 1 <= n - sx) v = get_sum(sx + x, max(sy - j - 1, y), sx + x + 1, min(sy + y, m - j));
          else v = 0;
          dp[i][j][x + 1][y] = max((int)dp[i][j][x + 1][y], dp[i][j][x][y] + v);
          if (j + y + 1 <= sy - 1) v = get_sum(max(sx - i - 1, x), sy - j - 2, min(sx + x, n - i), sy - j - 1);
          else v = 0;
          dp[i][j + 1][x][y] = max((int)dp[i][j + 1][x][y], dp[i][j][x][y] + v);
          if (j + y + 1 <= m - sy) v = get_sum(max(sx - i - 1, x), sy + y, min(sx + x, n - i), sy + y + 1);
          else v = 0;
          dp[i][j][x][y + 1] = max((int)dp[i][j][x][y + 1], dp[i][j][x][y] + v);
        }
      }
    }
  }
  PL(ans);
  return 0;
}


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

using namespace std;
using namespace __gnu_pbds;

#define fi first
#define se second
#define mp make_pair
#define pb push_back

typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef unsigned long long ull;
typedef long double ld;
typedef tree<ii, null_type, less<ii>, rb_tree_tag, tree_order_statistics_node_update> pbds;

int dp[311][311][311];
string s;

int solve(int l, int r, int k)
{
	if(k<0) return -int(1e9);
	if(l>r) return 0;
	if(dp[l][r][k]>=0) return dp[l][r][k];
	if(l==r) return 1;
	int ans = max(solve(l,r-1,k),solve(l+1,r,k));
	ans=max(ans,solve(l+1,r-1,k-(s[l]!=s[r]))+2);
	return (dp[l][r][k]=ans);
}

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin>>s; int k; cin>>k;
	memset(dp,-1,sizeof(dp));
	cout<<solve(0,int(s.length())-1,k)<<'\n';
}

#include <algorithm>
#include <cctype>
#include <cstring>
#include <cstdio>
using namespace std;
inline int read(int f = 1, int x = 0, char ch = ' ')
{
    while(!isdigit(ch = getchar())) if(ch == '-') f = -1;
    while(isdigit(ch)) x = x*10+ch-'0', ch = getchar();
    return f*x;
}
const int N = 3e2+5;
int n, m, f[N][N][N], ans; char s[N];
int main()
{
    scanf("%s", s+1), n = strlen(s+1), m = read();
    for(int i = 1; i <= n; ++i) f[0][i][i] = 1;
    for(int k = 0; k <= m; ++k)
        for(int l = 2; l <= n; ++l)
            for(int i = 1, j = l; j <= n; ++i, ++j)
            {
                f[k][i][j] = max(f[k][i+1][j], f[k][i][j-1]);
                if(s[i] == s[j]) f[k][i][j] = max(f[k][i][j], f[k][i+1][j-1]+2);
                if(k) f[k][i][j] = max(f[k][i][j], f[k-1][i+1][j-1]+2);
            }
    for(int i = 0; i <= m; ++i) ans = max(ans, f[i][1][n]);
    printf("%d\n", ans);
    return 0;
}


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

int main()
{
  int a,b,c,d,e,f,g,h,i,j,k,l,m,n,t,prothom,boro;
  cin>>n>>k;

   cin>>a;

  boro=a;

  for(int i=1;i<n;i++)
{
    cin>>b;
    a=__gcd(a,b);
    boro=max(boro,b);
}
  if(k<=boro && k%a==0)
    {
    cout<<"POSSIBLE"<<endl;
  }
  else
  {
    cout<<"IMPOSSIBLE"<<endl;
  }

}

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

int main()
{
	string s, c, p;
	int q, a, b;

	cin >> s >> q;
	while (q--) {
		cin >> c >> a >> b;
		int l = b - a + 1;
		if (c == "print")
			cout << s.substr(a, l) << endl;
		else if (c == "reverse")
			reverse(s.begin() + a, s.begin() + b + 1);
		else {
			cin >> p;
			s = s.replace(a, l, p);
		}
	}

	return 0;
}


#include<bits/stdc++.h>
using namespace std ;
#define ll long long
#define ld long double
#define ff first
#define ss second
const ll mod =   1e9 +7  ;
ll multiply(ll a, ll b ){ return ((a % mod) * (b % mod)) % mod; }
ll add(ll a, ll b) {     return ((a % mod) + (b % mod)) % mod; }
ll sub(ll a, ll b) { return ((a%mod) - (b % mod)+ mod) % mod ; }
////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
void solve(){
    ll n , m , v ,  p ;
    cin >> n >> m >> v >> p ;
    vector < ll > a(n) ;
    for( int i = 0 ; i < n ; i++) cin >> a[i]  ;
    sort(a.begin(),a.end());
    vector < ll > pre(n) ;
    pre[0] = a[0] ;
    for( int i = 1 ; i < n ; i++) pre[i] = pre[i-1] + a[i] ;
//    for( int i = 0 ; i < n ; i++) cout << a[i] << " "  ;
//    cerr << "\n" ;
    int ans = 0 ;
    for( int i = n-1 ; i >= 0  ; i--){
        ll r = n-p ;
        if(i>=r){
            ans++;
            continue ;
        }
        if(a[i]+m>=a[r]){
            int vote = v-p-i ;
            if(vote>0){
                ll sum = pre[r]-pre[i] ;
               // cout << i << " " << vote << " " << sum << " " << (a[i]+m)*(r-i)-sum<< "\n";
                if(m*vote<=(a[i]+m)*(r-i)-sum){
                    ans++;
                }
            }
            else{
                ans++;
            }
        }
        else{
            break ;
        }
    }
    cout << ans ;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t = 1 ;
    //cin >> t ;
    while(t--){
        solve( );
    }
}

#include <bits/stdc++.h>

#define debug(...) fprintf(stderr, __VA_ARGS__)

#ifndef AT_HOME
#define getchar() IO::myGetchar()
#define putchar(x) IO::myPutchar(x)
#endif

namespace IO {
	static const int IN_BUF = 1 << 23, OUT_BUF = 1 << 23;

	inline char myGetchar() {
		static char buf[IN_BUF], *ps = buf, *pt = buf;
		if (ps == pt) {
			ps = buf, pt = buf + fread(buf, 1, IN_BUF, stdin);
		}
		return ps == pt ? EOF : *ps++;
	}

	template<typename T>
	inline bool read(T &x) {
		bool op = 0;
		char ch = getchar();
		x = 0;
		for (; !isdigit(ch) && ch != EOF; ch = getchar()) {
			op ^= (ch == '-');
		}
		if (ch == EOF) {
			return false;
		}
		for (; isdigit(ch); ch = getchar()) {
			x = x * 10 + (ch ^ '0');
		}
		if (op) {
			x = -x;
		}
		return true;
	}

	inline int readStr(char *s) {
		int n = 0;
		char ch = getchar();
		for (; isspace(ch) && ch != EOF; ch = getchar())
			;
		for (; !isspace(ch) && ch != EOF; ch = getchar()) {
			s[n++] = ch;
		}
		s[n] = '\0';
		return n;
	}

	inline void myPutchar(char x) {
		static char pbuf[OUT_BUF], *pp = pbuf;
		struct _flusher {
			~_flusher() {
				fwrite(pbuf, 1, pp - pbuf, stdout);
			}
		};
		static _flusher outputFlusher;
		if (pp == pbuf + OUT_BUF) {
			fwrite(pbuf, 1, OUT_BUF, stdout);
			pp = pbuf;
		}
		*pp++ = x;
	}

	template<typename T>
	inline void print_(T x) {
		if (x == 0) {
			putchar('0');
			return;
		}
		static int num[40];
		if (x < 0) {
			putchar('-');
			x = -x;
		}
		for (*num = 0; x; x /= 10) {
			num[++*num] = x % 10;
		}
		while (*num){
			putchar(num[*num] ^ '0');
			--*num;
		}
	}

	template<typename T>
	inline void print(T x, char ch = '\n') {
		print_(x);
		putchar(ch);
	}

	inline void printStr_(const char *s, int n = -1) {
		if (n == -1) {
			n = strlen(s);
		}
		for (int i = 0; i < n; ++i) {
			putchar(s[i]);
		}
	}

	inline void printStr(const char *s, int n = -1, char ch = '\n') {
		printStr_(s, n);
		putchar(ch);
	}
}
using namespace IO;

int H, W, N;

int main() {
	read(H), read(W), read(N);
	print((N - 1) / std::max(H, W) + 1);
}


#include <iostream>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <list>
#include <set>
#include <unordered_set>
#include <vector>
#include <utility>
#include <algorithm>
#include <queue>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

constexpr ll inf = INT64_MAX / 4;
constexpr double pi = asin(1) * 2;
constexpr ll mod = 1000000007;

pair<ll, ll> extgcd(ll a, ll b) {
    if (b == 0)return make_pair(a, 0);
    auto t = extgcd(b, a % b);
    return make_pair(t.second, t.first - t.second * (a / b));
}

ll invmod(ll n) {
    return extgcd(n, mod).first;
}

class modint {
public:
    ll n;

    modint() = default;

    explicit modint(ll number) {
        n = ((number % mod) + mod) % mod;
    }

    bool operator==(modint e) {
        return n == e.n;
    }

    modint operator+(modint e) {
        return modint(n + e.n);
    }

    modint operator-(modint e) {
        return modint(n - e.n);
    }

    modint operator-(ll e) {
        return modint(n - e);
    }

    modint operator*(modint e) {
        return modint(n * e.n);
    }

    modint operator/(modint e) {
        return modint(n * invmod(e.n));
    }

};

template<class T>
T f1(T n, T m) {
    return m * m * (n * n * (n + T(1)) - (n * (n + T(1)) * (T(2) * n + T(1))) / T(3));
}

template<class T>
T f2(T n, T m) {
    return (f1(n, m) + f1(m, n)) / T(2);
}

template<class T>
T comb(T n, T k) {
    return k == T(0) ? T(1) : comb(n - T(1), k - T(1)) * n / k;
}

int main() {
    modint n, m, k;
    cin >> n.n >> m.n >> k.n;
    cout << (f2(n, m) * comb(n * m - 2, k - 2)).n << endl;
}

#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>
#define ll long long
#define MAX_N 200001

using namespace std;

long long MOD = 1000000007;

long long fact[MAX_N];
void factorial(int N){
    fact[0]=1;
    for(int i=0; i<N; i++){
        fact[i+1]=(i+1)*fact[i]%MOD;
    }
}

map<long long, long long> inv;
long long inverse(long long x){
    if (inv.count(x)){
        return inv[x];
    }
    long long p=MOD-2;
    long long ret=1;
    long long tmp=x;
    while(p>0){
        if(p%2==1)ret=ret*tmp%MOD;
        tmp=tmp*tmp%MOD;
        p/=2;
    }
    inv[x]=ret;
    return ret;
}

long long comb(int a, int b){
    long long ret=fact[a]*inverse(fact[a-b])%MOD;
    return ret*inverse(fact[b])%MOD;
}

int main(){
    ll N, M, K;
    cin >> N >> M >> K;

    factorial(200000);
    ll ans=0;
    for(ll y=0; y<N-1; y++){
        if(N*M-2<K-2)continue;
        ans+=((N+y)*(N-y-1)/2-y*(N-y-1))%MOD*M%MOD*M%MOD*comb(N*M-2,K-2)%MOD;
        ans%=MOD;
    }
    for(ll x=0; x<M-1; x++){
        if(M*N-2<K-2)continue;
        ans+=((M+x)*(M-x-1)/2-x*(M-x-1))%MOD*N%MOD*N%MOD*comb(M*N-2,K-2)%MOD;
        ans%=MOD;
    }
    cout << ans << endl;
}


#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
    int N; string A, B, C; cin >> N >> A >> B >> C;
    string str = "";

    vector<int> count(10e3, 0);
    for (int i = 0; i < N; ++i) {
        int x, y, z; x = y = z = 0;
        if (A[i] == B[i]) x++;
        if (B[i] == C[i]) y++;
        if (A[i] == C[i]) z++;
        if (x >= y && x >= z) str += A[i];
        else if (y >= x && y >= z) str += B[i];
        else if (z >= y && z >= x) str += C[i];
    }
    int cnt = 0;
    for (int i = 0; i < N; ++i) {
        if (A[i] != str[i]) cnt++;
        if (B[i] != str[i]) cnt++;
        if (C[i] != str[i]) cnt++;
    }
    printf("%d\n", cnt);
}

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<cstdio>
#include<queue>
#include<deque>
using namespace std;
typedef pair<int,int> ii;
typedef long long ll;
typedef pair<ll,ll> pll;
const int INF=1e9;
const ll MOD=1e9+7;

ll gcd(ll x,ll y){
    if(y==0) return 0;
    return gcd(y,x%y);
}

int dis2(int x1,int y1,int x2,int y2){
    return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
}

int main(){
    int n;cin>>n;
    string a,b,c;cin>>a>>b>>c;
    int ans=0;
    for(int i=0;i<n;i++){
        if(a[i]!=b[i]&&b[i]!=c[i]&&c[i]!=a[i]) ans+=2;
        else if(a[i]==b[i]&&b[i]==c[i]) continue;
        else ans++;
    }
    cout<<ans<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i, j, k) for(int i=(j); i<=(k); i++)
#define FFOR(i, j, k) for(int i=(j); i<(k); i++)
#define DFOR(i, j, k) for(int i=(j); i>=(k); i--)
#define bug(x) cerr<<#x<<" = "<<(x)<<'\n'
#define pb push_back
#define mp make_pair
#define bit(s, i) (((s)>>(i))&1LL)
#define mask(i) ((1LL<<(i)))
#define builtin_popcount __builtin_popcountll
#define __builtin_popcount __builtin_popcountll
using ll=long long; using ld=long double;
mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); const ld pi=acos(0)*2;
template <typename T> inline void read(T &x){char c; bool nega=0; while((!isdigit(c=getchar()))&&(c!='-')); if(c=='-'){nega=1; c=getchar();} x=c-48; while(isdigit(c=getchar())) x=x*10+c-48; if(nega) x=-x;}
template <typename T> inline void writep(T x){if(x>9) writep(x/10); putchar(x%10+48);}
template <typename T> inline void write(T x){if(x<0){ putchar('-'); x=-x;} writep(x);}
template <typename T> inline void writeln(T x){write(x); putchar('\n');}
template <typename CT, typename T> inline void reset_container(CT &c, int sz, T v){c.resize(sz); for(auto &x: c) x=v;}
#define taskname "C"
int n;
ll x;
ll start;
class subject{
public:
    ll b, l, u, w;
    void input(){
        read(b);
        read(l);
        read(u);
        start+=b*l;
        w=(x-b)*u+b*l;
    }
    ll cost(ll x){
        if(x<=b*l){
            return (x-1)/l+1;
        }
        else{
            x-=b*l;
            return b+(x-1)/u+1;
        }
    }
} s[100001];
ll f[100001];
int get(int i){
    int res=n;
    int low=0, high=n-1, mid;
    while(low<=high){
        mid=(low+high)/2;
        ll sum=f[mid];
        if(mid<i) sum+=s[i].w;
        if(sum>=start){
            res=mid;
            high=mid-1;
        }
        else low=mid+1;
    }
    return res;
}
int main(){
    #ifdef Aria
        if(fopen(taskname".in", "r"))
            freopen(taskname".in", "r", stdin);
    #endif // Aria
    read(n);
    read(x);
    FOR(i, 1, n) s[i].input();
    sort(s+1, s+n+1, [](subject A, subject B){
        return A.w>B.w;
    });
    ll ans=x*n;
    FOR(i, 1, n) f[i]=f[i-1]+s[i].w;
    FOR(i, 1, n){
        int j=get(i);
        ll res=x*j;
        if(j>i) res-=x;
        ll now=start-f[j];
        if(j>i) now+=s[i].w;
        if(now>0) ans=min(ans, res+s[i].cost(now));
        else ans=min(ans, res);
    }
    writeln(ans);
}

#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

int main(){
  string X,Y;
  int l=0;
 int point;

  cin>>X>>Y;
 int N[X.size()+1][Y.size()+1];

  for(int i=0;i<=Y.size();i++){

      N[0][i]=i;

  }

 for(int i=1;i<=X.size();i++){

      N[i][0]=i;

  }

  for(int i=1;i<=X.size();i++){
    for(int j=1;j<=Y.size();j++){
      if(X[i-1]==Y[j-1]){
	point=0;

      }else{
	point=1;
      }
      N[i][j]=min(min(N[i-1][j]+1,N[i][j-1]+1),N[i-1][j-1]+point);

  }
  }
  cout<<N[X.size()][Y.size()]<<endl;
 return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  string A;
  cin >> A;
  if(A.at(0) == '7') {
    cout << "Yes" << endl;
  }
  else if(A.at(1) == '7') {
    cout << "Yes" << endl;
  }
  else if(A.at(2) == '7') {
    cout << "Yes" << endl;
  }
  else{
    cout << "No" << endl;
  }
}

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

int main()
{
    string s ;
    cin>>s;
    bool a[27]={};
    for(int i=0;i<s.size();i++)
    {
        a[s[i]-'a']=true;
    }
    for(int i=0;i<27;i++)
    {
        if (i==26)
            cout<<"None";
        else if(!a[i])
            {
                char c='a';
                c=c+i;
                cout<<c;
               break;
            }
    }
    return 0;
}


#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <numeric>
#include <cmath>

using namespace std;

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

#define all(x) x.begin(),x.end()

const ll mod = 1e9+7;
const ll INF = 1e9;
const ll MAXN = 1e9;

int main()
{
	ll n,m;
	cin>>n>>m;
	ll ans=1;
	vector<int> a(n),b(m),flag(n*m,0);
	for(int i = 0; i < n; i++){
		cin>>a[i];
		a[i]--;
		if(flag[a[i]]>0){
			ans=0;
		}
		flag[a[i]]=1;
	}
	for(int i = 0; i < m; i++){
		cin>>b[i];
		b[i]--;
		if(flag[b[i]]>=2){
			ans=0;
		}
		if(flag[b[i]]>0) flag[b[i]]=3;
		else{
			flag[b[i]]=2;
		}
	}

	int j=-1,k=-1;
	for(int i = n*m-1; i >= 0 ; i--){
		if(flag[i]==3){
			j++;
			k++;
		}else if(flag[i]==2){
			ans*=j+1;
			ans%=mod;
			k++;
		}else if(flag[i]==1){
			ans*=k+1;
			ans%=mod;
			j++;
		}else{
			ans*=((j+1)*(k+1)-(n*m-(i+1)));
			ans%=mod;
		}
	}

	cout<<ans<<endl;

	return 0;
}

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

#define ff                  first
#define ss                  second
#define endl                "\n"
#define loop(i,s,e)         for(int i=s;i<e;i++)
#define int                 long long
#define vi                  vector<int>
#define S(v)                sort(v.begin(),v.end())
#define RS(v)               sort(v.rbegin(),v.rend())
#define R(v)                reverse(v.begin(),v.end())
#define mxpq(T)             priority_queue <T>
#define mnpq(T)             priority_queue<T,vector<T>,greater<T>>
#define prv(v)              for(auto &x : v)cout << x << " ";
#define piirv(v)            for(auto &x : v)cout << x.ff << " " << x.ss << endl;
#define prvv(v)             for(auto &x : v)for(auto &y : x.ss)cout << y << " ";
#define mp                  make_pair
#define pii                 pair<int,int>
#define mset(a,f)           memset(a , f , sizeof(a))
#define pb                  push_back
#define inf                 INT_MAX
#define INF                 LLONG_MAX
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> oset;

const int N = 1e5 + 6;
const int M = 1e9+7;
int A[N];
string s;
int n , d;
int dp[N][102][2];

int alpha(int id , int sum , int ok)
{
	if(id == n)return (sum == 0);
	int &abs = dp[id][sum][ok];
	if(abs != -1)return abs;
	int ans = 0;

	int k = s[id]-'0';
	if(ok)k = 9;

	loop(i,0,k+1)
	{
		if(i < k)
		{
			int nsum = (sum + i)%d;
			ans += alpha(id+1 , nsum , 1);
			ans %= M;
		}
		else
		{
			int nsum = (sum + i)%d;
			ans += alpha(id+1 , nsum , ok);
			ans %= M;
		}
	}

	return abs = ans;
}

void solve()
{
	cin >> s >> d;
	n = s.length();
	mset(dp,-1);
	int ans = alpha(0,0,0)-1;
	if(ans == -1)ans = M-1;
	cout << ans;
}

int32_t main()
{

cout<<fixed<<setprecision(16);

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

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

}


#include <bits/stdc++.h>
#define REP(i, e) for(int (i) = 0; (i) < (e); ++(i))
#define FOR(i, b, e) for(int (i) = (b); (i) < (e); ++(i))
#define ALL(c) (c).begin(), (c).end()
#define PRINT(x) cout << (x) << "\n"
using namespace std;
using ll = long long; using pint = pair<int, int>; using pll = pair<ll, ll>;
template<typename T> auto compare = [](T x, T y) -> bool{return (x < y);};
const int MOD = 1000000007;

ll N, M;
ll A[100010];

signed main(){
    cin >> N >> M;
    REP(i, N) cin >> A[i];
    ll sum = 0;
    map<ll, ll> mp;
    mp[0]++;
    REP(i, N){
        sum = (sum + A[i]) % M;
        mp[sum]++;
    }
    ll ans = 0;
    for(auto p : mp){
        ans += p.second * (p.second - 1) / 2;
    }
    PRINT(ans);
    return 0;
}

#define _USE_MATH_DEFINES
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <iomanip>
#include <deque>
#include <set>
#include <climits>
#include <memory>
#include <numeric>
#include <utility>

#define rep(i,a,b) for(int i=a;i<b;++i)
#define rrep(i,a,b) for(int i=a;i>=b;--i)
#define fore(i,a) for(auto &i:a)
#define INF INT_MAX/2;
#define PI 3.14159265358979323846264338327950L;
const int INF2 = 1001001001;
typedef long long ll;
using namespace std;
using vi = vector<int>;
using vll = vector<ll>;
ll mod = 1e9 + 7;
//ll llmax = 10000000000000000000ll;
const ll LINF = 1e18;
using namespace std;
using Graph = vector<vector<int>>;

int cnt_digit(ll N)
{
	int digit = 0;

	while (N > 0)
	{
		N /= 10;
		digit++;
	}
	return digit;
}

 // 最大公約数計算

ll gcd(ll a, ll b)
{
	if (b == 0) {
		return a;
	}
	else {
		return gcd(b, a % b);
	}
}
// 最小公倍数の計算

ll lcm(ll a, ll b)
{
	ll g = gcd(a, b);

	return a / g * b;
}

struct union_find
{
	vector<int> par, r;
	union_find(int n)
	{
		par.resize(n);
		r.resize(n);
		init(n);
	}

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

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

	void unite(int x, int y)
	{
		x = find(x);
		y = find(y);

		if (r[x] < r[y])
		{
			par[x] = y;
		}
		else
		{
			par[y] = x;
			if (r[x] == r[y])
			{
				r[x]++;
			}
		}
	}
};

const int MAX_N = 110000;

int memo[MAX_N];

int rec(int n) {
	if (n == 0)return 0;
	if (memo[n] != -1)return memo[n];

	int res = n;

	for (int pow6 = 1; pow6 <= n; pow6 *= 6)res = min(res, rec(n - pow6) + 1);

	for (int pow9 = 1; pow9 <= n; pow9 *= 9)res = min(res, rec(n - pow9) + 1);

	return memo[n] = res;
}

int calc(int x) {
	int ret = 0;
	while (x % 2 == 0) {
		x /= 2;
		ret++;
	}

	return ret;
}

int a[12][12];
int D;
ll G;
vector<ll> P, C;

//aのp乗を求めるアルゴリズム
long modpow(long a, int p) {
	if (p == 0)return 1;
	if (p % 2 == 0) {
		//pが偶数のとき
		int halfP = p / 2;
		long half = modpow(a, halfP);
		return half * half % mod;
	}
	else {
		//pが奇数の時は、
		//pを偶数にするために1減らす
		return a * modpow(a, p - 1) % mod;
	}

}

//(10*9*8)/(3*2*1);
//10*9*8 -> ansMul
//3*2*1 -> ansDiv;
long calcComb(int a, int b) {
	if (b > a - b) return calcComb(a, a - b);
	long ansMul = 1;
	long ansDiv = 1;
	rep(i, 0, b) {
		ansMul *= (a - i);
		ansDiv *= (i + 1);
		ansMul %= mod;
		ansDiv %= mod;
	}
	//ansMul /ansDivをやりたい
	//ansDivの逆元を使って求めよう。

	long ans = ansMul * modpow(ansDiv, mod - 2) % mod;
	return ans;

}

bool is_war(const vector<int>& x, const vector<int>& y) {
	for (int Z = -100; Z <= 100; Z++) {
		bool is_ok = true;
		rep(i, 0, x.size()) {
			if (x[i] >= Z) {
				is_ok = false;
			}
			rep(i, 0, y.size()) {
				if (y[i] < Z) {
					is_ok = false;
				}
			}

		}
		if (is_ok)return false;

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

	int n, m;
	cin >> n >> m;
	vector<int> x(n + 1),y(m+1);
	cin >> x[0] >> y[0];

	rep(i, 0, n) {
		cin >> x[i + 1];
	}
	rep(i, 0, m) {
		cin >> y[i + 1];
	}
	if (is_war(x, y)) {
		cout << "War" << endl;
	}
	else {
		cout << "No War" << endl;
	}

}


#include <bits/stdc++.h>
#define SIZE 300005
#define MOD 1000000007LL
#define INF 1 << 30
#define LLINF 1LL << 60
#define REP(i,n) for(int i=0;i<n;i++)
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define DOWN(i,b,a) for(int i=b;i>=a;i--)
#define SET(a,c) memset(a,c,sizeof a)
#define FORALL(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define FOREACH(i,c) for(auto (i) : (c))
#define BIT(i,j) ((i)>>(j))&1
#define ALL(o) (o).begin(), (o).end()
#define ERASE(o) (o).erase(unique((o).begin(),(o).end()), (o).end())
#define SQ(x) ((x)*(x))
using namespace std;
typedef long long ll;
typedef valarray<int> Array;
typedef pair<ll,ll> Pll;
typedef pair<int, int> Pii;
typedef pair<double, double> Pdd;
template<typename T> inline void priv(vector<T>a){REP(i,a.size()){cout<<a[i]<<((i==a.size()-1)?"\n":" ");}}
ll gcd(ll a,ll b){int c=max(a,b);int d=min(a,b);return c==0||d==0?c:gcd(c%d,d);}
ll lcm(ll a,ll b){return a==0||b==0?0:a*b/gcd(a,b);}

int a[144];

void flip(int x, int y)
{
  if(x>11||y>11||x<0||y<0) return;
  if(a[x+y*12])
  {
    a[x+y*12] = 0;
    flip(x+1,y);
    flip(x-1,y);
    flip(x,y+1);
    flip(x,y-1);
  }
}

void solve()
{
  int cnt = 0;
  REP(i,144) if(a[i])
  {
    cnt++;
    flip(i%12,i/12);
  }
  cout << cnt << endl;
}

int main()
{
  string s;
  int i = 0;
  while(cin >> s)
  {
    REP(j,12) a[i*12+j] = s[j]-'0';
    i=(++i)%12;
    if(i==0) solve();
  }
  return 0;
}

#include<iostream>
#include<string>
#define COL 12
#define ROW 12
using namespace std;
	int field[COL][ROW];

void mapping(int y, int x){
	//cout<<"mapping("<<y<<", "<<x<<")\n";
	if(field[y][x]==1){
		field[y][x]=0;
		if(y+1<COL) mapping(y+1,x);
		if(x+1<COL) mapping(y,x+1);
		if(y-1>=0)  mapping(y-1,x);
		if(x-1>=0)  mapping(y,x-1);
	}
	return;
}

int main(){
	string str;
	int i, j,cnt;
	bool loop = true;
	while(true){
		for(i=0;i<COL;i++){
			cin>>str;
			if(cin.eof()){
				loop = false;
				break;
			}
			for(j=0;j<ROW;j++){
				field[i][j] = str[j] - '0';
			}
		}
		if(loop==false) break;
		cnt=0;
		for(i=0;i<COL;i++){
			for(j=0;j<ROW;j++){
				if(field[i][j]==1){
					mapping(i,j);
					cnt++;
				};
			}
		}
		cout<<cnt<<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 N;
  string s, t;
  cin >> N;
  cin >> s >> t;

  int len=s.size() + t.size();
  rep(i,s.size()) {
    if (t.find(s.substr(i)) != string::npos) {
      len -= (s.size() - i);
      break;
    }
  }

  cout << len << endl;
  return 0;
}

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=2e6+500;
int n;char st[N];
int nxt[N];
int main()
{
    scanf("%d",&n);
    scanf("%s",st+1);scanf("%s",st+n+1);
    for(int i=1;i<=n;i++)swap(st[i],st[i+n]);
    int j=0;
    for(int i=2;i<=2*n;i++)
    {
        while(j&&st[j+1]!=st[i])j=nxt[j];
        if(st[j+1]==st[i])++j;
        nxt[i]=j;
    }
    int t=nxt[2*n];while(t>n)t=nxt[t];
    cout<<2*n-t<<endl;
}


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

int m, nMin, nMax;
int P[210];
pair<int, int> ans[210];

signed main()
{
    while (true) {
        cin >> m >> nMin >> nMax;
        if (m == 0 && nMin == 0 && nMax == 0) break;

        REP(i,m) cin >> P[i];
        sort(P, P + m, greater<int>());

        int idx = 0;
        for (int i=nMin; i<=nMax; i++) {
            ans[idx++] = make_pair(P[i-1] - P[i], i);
        }

        sort(ans, ans + idx);
        cout << ans[idx-1].second << endl;
    }
}

#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); }
template<class T> void operator>> (istream& ist, vector<T>& vs) { for(auto& e: vs) cin >> e; }

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

int main() {

  int M, N[2];
  for(; cin >> M >> N[0] >> N[1] && M;) {
    vector<int> vs(M); cin >> vs;
    int maxgap = 0;
    int maxnum = -1;
    REP(num, N[0], N[1] + 1) {
      if(maxgap <= vs[num - 1] - vs[num]) {
        maxgap = vs[num - 1] - vs[num];
        maxnum = num;
      }
    }

    cout << maxnum << endl;
  }

  return 0;
}


#include <bits/stdc++.h>

#define repd(i, a, b) for (ll i = (a); i < (b); i++)
#define repb(i, n) for (ll i = (n)-1; i >= 0; i--)
#define rep(i, n) repd(i, 0, n)

using namespace std;

using ll = long long;
using ul = unsigned long long;
using ld = long double;
ll mod = 1000000007;

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

    set<ll> div;
    for (int i = 1; i * i < m; i++) {
        if (m % i == 0) {
            div.insert(i);
            div.insert(m / i);
        }
    }

    ll ans = 1;
    for (auto iter = div.begin(); iter != div.end(); iter++) {
        if (m / (*iter) >= n) {
            ans = (*iter);
        }
    }
    cout << ans << endl;

    return 0;
}

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

const ll LINF = 1e18;
const int INF = 1e9;
const ll MOD = 1000000007;

int main(){

    int r, g;
    cin >> r >> g;
    cout << 2*g - r << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  string s;
  cin >> n >> s;
  long long r = 0, g = 0, b = 0;
  for(int i = 0; i < n; i++) {
    if(s.at(i) == 'R') r++;
    else if(s.at(i) == 'G') g++;
    else b++;
  }
  long long sum = r * g * b;
  for(int i = 0; i < (n - 2); i++) {
    for(int j = i + 1; j < (n - 1); j++) {
      if(s.at(i) != s.at(j)) {
        if(j + (j - i) >= n) {
          continue;
        }
        char x = s.at(j + (j - i));
        if(s.at(i) != x && s.at(j) != x) sum--;
      }
    }
  }
  cout << sum << endl;
}

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

using namespace std;
using ll = long long int;

template <class T> ostream &operator<<(ostream &os, vector<T> &v) {
  for (auto i = v.begin(); i != v.end(); i++) {
    os << *i << " ";
  }
  return os;
}

void solve(std::string A){
  ll x = 0;
  ll len = A.size();
  for(ll i=0; i<26; i++) {
    ll cnt = 0;
    for(auto c : A) {
      if(c == 'a'+i)
	cnt++;
    }
    x += cnt*(cnt-1) / 2;
  }
  std::cout << (len * (len-1))/2 - x + 1<< std::endl;
}

int main(){
  std::string A;
  std::cin >> A;
  solve(A);
  return 0;
}