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

int main(){
  int k,x;
  cin >> k >> x;
  for(int i = x-k+1; i <= x + k - 2; i++){
    cout << i << " ";
  }
  cout << x + k - 1 << endl;
}

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<math.h>
#include<map>
using namespace std;
int main() {
    int x,y;
    cin >> x >> y;
    int ans = 0;
    switch (x)
    {
    case 1:
        ans += 300000;
        switch (y)
        {
        case 1:
            ans += 700000;
            break;
        case 2:
            ans += 200000;
            break;
        case 3:
            ans += 100000;
            break;
        }
        break;
    case 2:
        ans += 200000;
        switch (y)
        {
        case 1:
            ans += 300000;
            break;
        case 2:
            ans += 200000;
            break;
        case 3:
            ans += 100000;
            break;
        }
        break;
    case 3:
        ans += 100000;
        switch (y)
        {
        case 1:
            ans += 300000;
            break;
        case 2:
            ans += 200000;
            break;
        case 3:
            ans += 100000;
            break;
        }
        break;
    default:
        switch (y)
        {
        case 1:
            ans += 300000;
            break;
        case 2:
            ans += 200000;
            break;
        case 3:
            ans += 100000;
            break;
        }
    }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
#define sz(x) (int((x).size()))
#define pb push_back
#define eb emplace_back
#define all(x) (x).begin(), (x).end()
template<typename T> bool domax(T &a, T b) { return (b > a ? (a = b, true) : false); }
template<typename T> bool domin(T &a, T b) { return (b < a ? (a = b, true) : false); }
typedef long long ll;

const int maxc = 105, inf = 1e9;

int Y, X, s[maxc][maxc], ey, ex, dp[maxc][maxc][maxc][maxc], ans;
char g[maxc][maxc];
int bly, blx, bsy, bsx;

int sum(int ly, int lx, int sy, int sx) {
    if (bly < ly) ly = bly;
    if (blx < lx) lx = blx;
    if (bsy > sy) sy = bsy;
    if (bsx > sx) sx = bsx;
    return std::max(0, s[ly+1][lx+1] - s[ly+1][sx] - s[sy][lx+1] + s[sy][sx]);
}

int main() {
    scanf("%d%d", &Y, &X);
    for (int y = 0; y < Y; y++) scanf(" %s", g[y]);
    for (int y = 0; y < Y; y++) for (int x = 0; x < X; x++) {
        if (g[y][x] == 'E') { ey = y; ex = x; }
        s[y+1][x+1] = s[y+1][x] + s[y][x+1] - s[y][x];
        if (g[y][x] == 'o') s[y+1][x+1]++;
    }
    int W = ex+1, E = X-ex;
    int N = ey+1, S = Y-ey;
    for (int w = 0; w < W; w++) for (int e = 0; e < E; e++) for (int n = 0; n < N; n++) for (int s = 0; s < S; s++) {
        dp[w][e][n][s] = -inf;
    }
    dp[0][0][0][0] = 0;
    for (int w = 0; w < W; w++) for (int e = 0; e < E; e++) for (int n = 0; n < N; n++) for (int s = 0; s < S; s++) {
        domax(ans, dp[w][e][n][s]);
        //if (ans == 5) {
        //    printf("%d %d %d %d\n", w, e, n, s);
        //    return 0;
        //}
        domax(dp[w+1][e][n][s], dp[w][e][n][s]);
        domax(dp[w][e+1][n][s], dp[w][e][n][s]);
        domax(dp[w][e][n+1][s], dp[w][e][n][s]);
        domax(dp[w][e][n][s+1], dp[w][e][n][s]);
        bsx = e; blx = X-1-w;
        bsy = s; bly = Y-1-n;
        if (e <= ex-(w+1))         domax(dp[w+1][e][n][s], dp[w][e][n][s] + sum(ey+s, ex-(w+1), ey-n, ex-(w+1)));
        if (w <= X-1 - (ex+(e+1))) domax(dp[w][e+1][n][s], dp[w][e][n][s] + sum(ey+s, ex+(e+1), ey-n, ex+(e+1)));
        if (s <= ey-(n+1))         domax(dp[w][e][n+1][s], dp[w][e][n][s] + sum(ey-(n+1), ex+e, ey-(n+1), ex-w));
        if (n <= Y-1 - (ey+(s+1))) domax(dp[w][e][n][s+1], dp[w][e][n][s] + sum(ey+(s+1), ex+e, ey+(s+1), ex-w));
        //if (dp[0][0][0][1] == 3) {
        //    printf("wtf %d %d %d %d\n", w, e, n, s);
        //    return 0;
        //}
        //if (dp[0][1][0][1] == 5) {
        //    printf("hi %d %d %d %d\n", w, e, n, s);
        //    return 0;
        //}
    }
    printf("%d\n", ans);
}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <utility>
#include <queue>
#include <climits>
using namespace std;

int mcm(vector<int>& p)
{
    vector<vector<int> > m(p.size() - 1, vector<int>(p.size() - 1));
    for (int i = 0; i < m.size(); i++) {
        m[i][i] = 0;
    }
/*
 * l == number of targets
 * i == left most of targets
 */
    for (int l = 2; l <= m.size(); l++) {
        for (int i = 0; i < m.size() - l + 1; i++) {
            int j = i + l - 1;
            m[i][j] = INT_MAX;
            for (int k = i; k < j; k++) {
                m[i][j] =
                    min(m[i][j],
                        m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]);
            }
        }
    }
    return m[0][m.size() - 1];
}

int main()
{
    int n;
    cin >> n;
    vector<int> p(n + 1);
    for (int i = 1; i < n + 1; i++) {
        cin >> p.at(i - 1) >> p.at(i);
    }
    cout << mcm(p) << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main()
  {int A, B, c{}; cin >> A >> B;
  for (int i{A}; i <= B; ++i)
    {auto s{to_string(i)}, t{s}; reverse(begin(t), end(t));
    c += s == t;}
  cout << c;}

#include<bits/stdc++.h>
#define reg register
using namespace std;
inline int  read() {
    reg int s = 0, t = 0; reg char ch = getchar();
    while(ch > '9' || ch < '0') t |= ch == '-', ch = getchar();
    while(ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
    return t ? -s : s;
}
int n, m, a[301][301], d[301], pos[301], sum[301], minn = 190090, ans;
int main()
{
    n = read(); m =  read();
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++) a[i][j] = read();
        sum[a[i][1]]++;
    }
    for(int i = m; i >= 1; i--){
        ans = 0;
        for(int j = 1; j <= m; j++) ans = max(ans, sum[j]);
        minn = min(minn, ans);
        for(int j = 1; j <= m; j++) {
            if(sum[j] == ans){   pos[j] = 1; break;}
        }
        for(int j = 1; j <= m; j++) sum[j] = 0;
        for(int j = 1; j <= n; j++)
            for(int k = 1; k <= m; k++){
                if(!pos[a[j][k]]) {sum[a[j][k]]++; break;}
            }
    }
    cout << minn;
}


#include <iostream>
#include <algorithm>
#include <iomanip>
#include <string>
#include <vector>
#include <math.h>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#define PI 3.14159265359
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pai;
typedef pair<ll, ll> pal;
const int MOD = 1e9+7;
const ll LLINF = 1e18;

int main(){
	string s;
	cin >> s;
	cout << "2018" << s.substr(4, 6) << endl;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG //これつけるとA[N]でもいいらしい
//for文のマクロ
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define mp(a,b) make_pair(a,b)
#define big 1000000007
#define all(a) sort((a).begin(),(a).end()) //ソートのマクロ
#define Re(a) reverse((a).begin(),(a).end())
#define YN(a) if(a){cout<<"Yes"<<endl;}else cout<<"No"<<endl;//条件によってYes、Noを出力する
const int MOD=1000000007;
const double pi = 3.141592653589793;
int main(){
    string s;
    cin>>s;
    int n=s.length();
    if(n==2){
        if(s[0]==s[1])cout<<"1 2"<<endl;
        else cout<<"-1 -1"<<endl;
        return 0;
    }
    rep(i,n-1){
        string t = s.substr(i,3);
        if(t[0]==t[1]||t[1]==t[2]||t[0]==t[2]){
            cout<<i+1<<" "<<i+3<<endl;
            return 0;
        }
    }
    cout<<-1<<" "<<-1<<endl;
}


///not today

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

typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int> > pipii;
typedef pair<long long, long long> pll;

#define SZ(x) (int)(x).size()
#define pub push_back
#define pob pop_back
#define puf push_front
#define pof pop_front
#define xmax(x, y) (x) = max((x), (y))
#define xmin(x, y) (x) = min((x), (y))
#define F first
#define S second
#define int long long
#define accept_sho ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")
#define lc (v << 1)
#define rc ((v << 1)| 1)
#define MID ((R + L) >> 1)

const int mod = 998244353, maxn = 1e6 + 3;
int fc[maxn];

int pw(int a, int b){
      int ans = 1;
      for(int i = 30; i >= 0; i --){
            ans *= ans;                                                    ans %= mod;
            if(b & (1 << i)){
                  ans *= a;                                                ans %= mod;
            }
      }
      return ans;
}

int c(int k, int n){
      if(k == 0){
            return 1;
      }
      if(k > n){
            return 0;
      }
      int ans = fc[n];
      ans *= pw(fc[k], mod - 2);                                           ans %= mod;
      ans *= pw(fc[n - k], mod - 2);                                       ans %= mod;
      return ans;
}

int32_t main(){
      accept_sho
      int n, m;
      cin >>n >>m;
      fc[0] = 1;
      for(int i = 1; i < maxn - 1; i ++){
            fc[i] = fc[i - 1] * i;                                         fc[i] %= mod;
      }
      int ans = max(n, m);
      for(int i = 1; i <= min(n, m); i ++){
            int x = ( c(n - i, n + m - (2 * i)) * c(i, 2 * i) )% mod;
            x *= pw(c(n, n + m) ,mod - 2);                                 x %= mod;
            x *= pw(2, mod - 2);                                           x %= mod;
            ans = (ans + x)% mod;
      }
      cout <<ans <<endl;
      return false;
}

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000, mod = 998244353, inv2 = (mod + 1) / 2;
int n, m, s, w, d, w2, ans;
int fac[maxn + 10], ifac[maxn + 10], inv[maxn + 10];

inline int add(int x, int y) {
	x += y; return x < mod ? x : x - mod;
}
inline int dec(int x, int y) {
	x -= y; return x < 0 ? x + mod : x;
}
inline int mul(int x, int y) {
	return 1ll * x * y % mod;
}

void prework() {
	fac[0] = ifac[0] = 1;
	for (int i = 1; i <= maxn; ++i) {
		fac[i] = mul(fac[i - 1], i);
		inv[i] = i == 1 ? 1 : dec(0, mul(mod / i, inv[mod % i]));
		ifac[i] = mul(ifac[i - 1], inv[i]);
	}
}

int comb(int x, int y) {
	return y < 0 || y > x ? 0 : mul(fac[x], mul(ifac[y], ifac[x - y]));
}

int f(int x, int y) {
	return comb(x + y, x);
}

int main() {
	prework();
	scanf("%d%d", &n, &m);
	w = comb(n + m - 1, n); w2 = comb(n + m - 1, m); d = 1;
	s = add(s, add(w, w2));
	for (int i = m - 2; i >= -n - 1; --i) {
		ans = add(ans, mul(s, inv[d]));
		++d;
		if (d & 1) {
			w = add(w, mul(f(i + d / 2, n - d / 2), f(m - (i + d / 2) - 2, d / 2)));
			w2 = add(w2, mul(f(m - d / 2, n - (d - d / 2)), f(d / 2, d - d / 2 - 2)));
		} else {
			w = dec(w, mul(f(i + d / 2, n - d / 2), f(m - (i + d / 2) - 1, d / 2 - 1)));
			w2 = dec(w2, mul(f(m - d / 2, n - (d - d / 2)), f(d / 2 - 1, d - d / 2 - 1)));
		}
		s = add(s, add(w, w2));
	}
	printf("%d", mul(ans, mul(ifac[n + m], mul(fac[n], fac[m]))));
}


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

using namespace std;

int main() {
    int n, it, it2;
    it = 0;
    it2 = 0;
    char a;
    cin >> n;
    int sum = n;
    vector<char> str;
    rep(i , n){
        cin >> a;
        str.push_back(a);
    }
    rep(i , n){
        if (i == 0){

            it2 = int(count(str.begin() + 1, str.end(), 'E'));
        }
        else{
            if (str.at(i - 1) == 'W')
                it++;
            if (str.at(i) == 'E')
                it2--;
        }

        sum = min(sum , it + it2);

    }
    cout << sum  << endl;

}

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

int main() {
  int N;
  string S;
  cin >> N >> S;
  vector<int> E(N + 1), W(N + 1);
  for (int i = 1; i < N + 1; i++) {
    E.at(i) = E.at(i - 1) + (S.at(i - 1) == 'E');
    W.at(i) = W.at(i - 1) + (S.at(i - 1) == 'W');
  }
  int ans = 2e9;
  for (int i = 0; i < N + 1; i++) {
    ans = min(ans, E.at(N) - E.at(i) + W.at(i));
  }
  cout << ans << "\n";
}


#include <iostream>
using namespace std;

int main(){
	while (true)
	{
		int n, a[5001] = {};
		long long int ans = -100000, sum;
		cin >> n;
		if (n == 0) { break; }
		for(int i = 0;i<n;i++){
			cin >> a[i];
		}
		for(int i = 0;i<n;i++){
			sum = 0;
			for(int j = i;j<n;j++){
				sum += a[j];
				if(sum > ans){
					ans = sum;
				}
			}
		}

		cout << ans << endl;
	}
	return 0;
}

#include <iostream>
#include <ccomplex>
#include <vector>
#include <cassert>
#include <utility>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <functional>
#include <cmath>
#include <iomanip>
#include <map>
#include <numeric>
#include <list>
#include <assert.h>
#include <math.h>
#include <valarray>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <complex>
#include <list>
#include <time.h>
#include <stack>
#include <locale>
#include <clocale>
#include <ctype.h>
#include <wchar.h>

using namespace std;
typedef long long int LL;
typedef pair<long long int, long long int> pii;
typedef pair<double, double> pdd;

#define SORT(c) sort((c).begin(),(c).end())
#define BACKSORT(c) sort((c).begin(),(c).end(),std::greater<LL>())
#define FOR(i,a,b) for(LL i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

int xcomp(vector<LL>& a, vector<LL>& b) {
	return a[0] < b[0];
}

#define XSORT(c) sort((c).begin(),(c).end(),xcomp)

#define ALL(x) (x).begin(),(x).end()
LL mod = 1000000007;

int main() {
	int N;
	cin >> N;
	REP(i, N) {
		int a1 = 0;
		int a2 = 0;
		int a3 = 0;
		int out = 0;
		int pt = 0;
		while (true) {

			string s;
			cin >> s;
			if (s[1] == 'I') {
				if (a3 == 1) {
					a3 = 0;
					pt++;
				}
				if (a2 == 1) {
					a2 = 0;
					a3 = 1;
				}
				if (a1 == 1) {
					a1 = 0;
					a2 = 1;
				}
				a1 = 1;
			}
			else
				if (s[1] == 'U') {
					out++;
					if (out == 3) {
						break;
					}
				}
				else {
					if (a1 == 1) {
						a1 = 0;
						pt++;
					}
					if (a2 == 1) {
						a2 = 0;
						pt++;
					}
					if (a3 == 1) {
						a3 = 0;
						pt++;
					}
					pt++;
				}
		}
		cout << pt << endl;
	}
}


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

int main(){
	int n; cin>>n;
	set<int> st;
	rep(i,n){
		int a; cin>>a;
		if(st.count(a)==1) st.erase(a);
		else st.insert(a);
	}
	cout<<st.size()<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int> P;
int INF = 1e9+7;
int mod = 1e9+7;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
signed main() {
    int N;
    cin >> N;
    vector<int>A(N);
    vector<int>B(N);
    vector<int>C(N);
    for(int i = 0; i < N; i++) cin >> A[i];
    for(int i = 0; i < N; i++) cin >> B[i];
    for(int i = 0; i < N; i++) cin >> C[i];
    sort(A.begin(),A.end());
    sort(C.begin(),C.end());
    int ans = 0;
    for(int i = 0; i < N; i++) {
        int cnt = 1;
        int it = lower_bound(A.begin(),A.end(),B[i])-A.begin();
        cnt*=it;
        it = C.end()-upper_bound(C.begin(),C.end(),B[i]);
        cnt*=it;
        ans+=cnt;
    }
    cout << ans << endl;
}


#include <iostream>
using namespace std;

int main()
{
  string test;
  getline(cin,test);

  if (test[0] == 'A' && test[1] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[1] == 'A' && test[2] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[2] == 'A' && test[3] == 'C')
  {
    cout << "Yes" << endl;
  }
  else if(test[3] == 'A' && test[4] == 'C')
  {
    cout << "Yes" << endl;
  }
  else
  cout << "No" << endl;
}

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

#define int long long
typedef pair<int, int> P;
#define mod 1000000007
#define INF (1LL<<60)

#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define repi(itr, ds) for (auto itr = ds.begin(); itr != ds.end(); itr++)
#define YES puts("YES")
#define Yes puts("Yes")
#define NO  puts("NO")
#define No  puts("No")
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }

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

#if 1
//-------------
// DUMPマクロ
// https://www.creativ.xyz/dump-cpp-652/

// vector
template <typename T>
istream& operator>>(istream& is, vector<T>& vec) {
    for (T& x : vec) is >> x;
    return is;
}
// pair
template <typename T, typename U>
ostream& operator<<(ostream& os, pair<T, U>& pair_var) {
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}
// vector
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
// map
template <typename T, typename U>
ostream& operator<<(ostream& os, map<T, U>& map_var) {
    os << "{";
    repi(itr, map_var) {
        os << *itr;
        itr++;
        if (itr != map_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
// set
template <typename T>
ostream& operator<<(ostream& os, set<T>& set_var) {
    os << "{";
    repi(itr, set_var) {
        os << *itr;
        itr++;
        if (itr != set_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}

#define DUMPOUT cerr

void dump_func() {
    DUMPOUT << endl;
}
template <class Head, class... Tail>
void dump_func(Head&& head, Tail&& ... tail) {
    DUMPOUT << head;
    if (sizeof...(Tail) > 0) {
        DUMPOUT << ", ";
    }
    dump_func(std::move(tail)...);
}
#ifdef DEBUG
#define DEB
#define dump(...)                                                              \
    DUMPOUT << "  " << string(#__VA_ARGS__) << ": "                            \
            << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]"        \
            << endl                                                            \
            << "    ",                                                         \
        dump_func(__VA_ARGS__)
#else
#define DEB if (false)
#define dump(...)
#endif
#endif

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

    if(s.find("AC")==s.npos) No;
    else Yes;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2000+10,mod=1e9+7;
ll f[maxn][maxn];
ll s[maxn*maxn+10],invs[maxn*maxn+10];
int n,m;
inline void read(int &x){
	char c=getchar();
	int f=1;
	x=0;
	while(c<'0' || c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();}
	x*=f;
}
inline long long ksm(ll x,int y){
	ll sum=1;
	while(y){
		if(y&1){sum=(sum*x)%mod;}
		y/=2;
		x=(x*x)%mod;
	}
	return sum%mod;
}
inline ll cal(int x,int y){
	//cout<<s[x]<<" "<<s[y]<<endl;
	ll sum2=1,sum1=1,sum=0;
	//for(register int i=1;i<=y;i++)sum1=(sum1*i)%mod;
	//for(register int i=x-y+1;i<=x;i++)sum2=(sum2*i)%mod;
	//sum2=s[x];sum1=(s[x-y]*s[y])%mod;
	//sum=(sum2*ksm(sum1,mod-2))%mod;
	sum=((s[x]*invs[y])%mod*invs[x-y])%mod;
	//cout<<sum<<endl;
	return sum%mod;
}
int main(){
	int i,j,k;
	read(n);read(m);
	//cout<<n<<" "<<m<<endl;
	if(m==1){cout<<1<<endl;return 0;}
	f[0][0]=1;
	s[0]=1;
	//for(register int i=1;i<=n;i++)f[i][0]=1;
	for(register int i=1;i<=maxn*maxn;i++){s[i]=(s[i-1]*i)%mod;}
	invs[maxn*maxn]=ksm(s[maxn*maxn],mod-2);
	for(register int i=maxn*maxn-1;i>=0;i--)invs[i]=(invs[i+1]*(i+1))%mod;
	for(register int i=1;i<=n;i++)
		for(register int j=0;j<=i;j++){
			if(!j)f[i][j]=f[i-1][j]%mod;
			else f[i][j]=(f[i-1][j]+((f[i][j-1]*(n-j+1))%mod*cal(n*m-(j-1)*(m-1)-i-1,m-2)))%mod;
		}
	cout<<f[n][n]<<endl;
	return 0;
}

#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#include <bits/stdc++.h>

#define int ll
//#define double long double
#define endl '\n'
#define all(C) (C).begin(), (C).end()
#define rall(C) (C).rbegin(), (C).rend()
#define mp make_pair
#define pb emplace_back
#define dbg(x) cerr << #x << " : " << x << endl
//#define PI 3.141592653589

using namespace std;

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair <int, int>;
using pld = pair <ld, ld>;

/*
const ll MAX_MEM = 25e7;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

template <class T>
istream& operator>> (istream &in, vector <T> &a)
{
    for (auto &i : a)
        in >> i;
    return in;
}

template <class T>
ostream& operator<< (ostream &out, vector <T> a)
{
    for (auto &i : a)
        out << i << ' ';
    return out;
}

template <class T, class U>
istream& operator>> (istream &in, pair <T, U> &p)
{
    in >> p.first >> p.second;
    return in;
}

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

inline void Start()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    //freopen("lol.in", "r", stdin);
    //freopen("lol.out", "w", stdout);
}

const int P = 1e9 + 7;
int add(int a, int b)
{
    return a + b >= P ? a + b - P : a + b;
}
int mul(int a, int b)
{
    return a * b % P;
}
int bpow(int a, int n)
{
    int res = 1;
    while (n)
    {
        if (n & 1)
            res = mul(res, a);
        a = mul(a, a);
        n >>= 1;
    }
    return res;
}
int rev(int x)
{
    return bpow(x, P - 2);
}
int sub(int a, int b)
{
    return add(a, P - b);
}
int divi(int a, int b)
{
    return mul(a, rev(b));
}
struct combinations
{
    vector <int> fact, revfact;
    combinations() {}
    combinations(int n)
    {
        fact.assign(n, 1);
        revfact.assign(n, 1);
        for (int i = 1; i < n; ++i)
            fact[i] = mul(fact[i - 1], i), revfact[i] = divi(revfact[i - 1], i);
    }
    int operator() (int n, int k)
    {
        return mul(fact[n], mul(revfact[k], revfact[n - k]));
    }
};

signed main()
{
    Start();
    int n, k;
    cin >> n >> k;
    combinations c(2001 * 2001);
    if (k == 1)
        return cout << 1, 0;
    vector <vector <int>> dp(n + 1, vector <int> (n + 1));
    dp[0][0] = 1;
    for (int i = 0; i <= n; ++i)
    {
        for (int j = (i ? 0 : 1); j <= n; ++j)
        {
            if (j < i)
                continue;
            if (i)
                dp[i][j] = add(dp[i][j], dp[i - 1][j]);
            if (j)
                dp[i][j] = add(dp[i][j], mul(dp[i][j - 1], c(i + j * (k - 1) - 1, k - 2)));

        }
    }
    cout << mul(dp[n][n], c.fact[n]);
    return 0;
}


#include <iostream>
int main(){
	int n=0,A=0,B=0;
	while(std::cin >> n, n){
		for(int i=0;i<n;i++){
			int a=0,b=0;
			std::cin>>a>>b;
			int ab=a+b;
			if(a>b){
				A+=ab;
			}else{
				if(a<b){
					B+=ab;
				}else{
					A+=a;
					B+=b;
				}
			}
		}
		std::cout<<A<<" "<<B<<std::endl;
		A=0,B=0;
	}
	return 0;
}


#include <bits/stdc++.h>
#define reg register
#define ll long long
#define ull unsigned long long
using namespace std;
const int MAXN = 110;
int n;
ll a[MAXN];
void work() {
  scanf("%d", &n);
  for(reg int i = 1; i <= n; ++i) scanf("%lld", &a[i]);
  int ans = 0;
  for(reg int i = 1; i <= n; ++i) {
    for(reg int j = i + 1; j <= n; ++j) {
      for(reg int k = j + 1; k <= n; ++k) {
        if(a[i] != a[j] && a[j] != a[k] && a[i] != a[k]) {
          if(a[i] + a[j] > a[k] && a[i] + a[k] > a[j] && a[j] + a[k] > a[i]) ++ans;
        }
      }
    }
  }
  printf("%d\n", ans);
}
signed main() {
  int _ = 1;
  // scanf("%d", &_);
  while(_--) {
    work();
  }
  return 0;
}

#include<bits/stdc++.h>
// Begin Header {{{
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i,n) for(ll i=0; i<n; i++)
#define loop(i, j, n) for(ll i=j; i<n; i++)
#define all(x) (x).begin(), (x).end()
constexpr int INF  = 0x3f3f3f40;
const long long mod=1e9+7;
const long double PI = acos(0);
template <class T>void UNIQUE(vector<T> &x){
	sort(all(x));
	x.erase(unique(all(x)), x.end());
}

// }}} End Header
int main() {
	int n, ans = 0;
	cin >> n;
	vector<ll> l(n);
	map<ll, ll> dict;
	rep(i,n){
		cin >> l[i];
		dict[l[i]]++;
	}
	UNIQUE(l);
	if(l.size()<3){
		cout << 0 << endl;
		return 0;
	}
	rep(i,l.size()-2){
		loop(j, i+1, l.size()-1){
			loop(k, j+1, l.size()){
				if(l[i]+l[j] > l[k]){
					//cout << l[i] << l[j] << l[k] << endl;
					ans+=(dict[l[i]]*dict[l[j]]*dict[l[k]]);
				}
			}
		}
	}
	cout << ans << endl;

	return 0;
}


#include <stdio.h>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <queue>
#include <set>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <complex>

using ll = long long int;
using namespace std;

int main(){

  ll N, tmp;
  vector<ll> A;
  cin >> N;
  for(ll i = 0; i < N; i++){
    cin >> tmp;
    A.push_back(tmp);
  }

  // if N is even
  if(N%2 == 0){
    cerr << "N is even." << endl;
    vector<ll> accum(N);
    accum[0] = A[0];
    for(ll i = 2; i < N; i+=2){
      accum[i] = accum[i-2] + A[i];
    }
    accum[N-1] = A[N-1];
    for(ll i = N-3; i >= 1; i-=2){
      accum[i] = accum[i+2] + A[i];
    }
    ll ans = max(accum[N-2], accum[1]);
    for(ll i = 0; i<=N-4; i+=2){
      ans = max(ans, accum[i]+accum[i+3]);
    }

    cerr << "Answer:" << endl;
    cout << ans << endl;

    return 0;
  }
  // N is odd
  else{
    cerr << "N is odd." << endl;
    vector<ll> accum(N);
    accum[0] = A[0];
    for(ll i = 2; i < N; i++){
      accum[i] = accum[i-2] + A[i];
    }
    accum[N-2] = A[N-2];
    for(ll i = N-4; i >= 1; i-=2){
      accum[i] = accum[i+2] + A[i];
    }
    vector<ll> diff(N);
    for(ll i = 1; i <= N-4; i+=2){
      diff[i] = accum[i-1] + accum[i+2] - accum[1];
    }
    for(ll i = 2; i <= N-3; i+=2){
      diff[i] = accum[N-1]-accum[i] + accum[1] - accum[i+1] - accum[1];
    }
    diff[N-2] = accum[N-3] - accum[1];
    diff[0] = accum[2] - accum[1];

    vector<ll> eomax(N);
    eomax[N-3] = diff[N-3];
    for(ll i = N-5; i >= 0; i-=2){
      eomax[i] = max(eomax[i+2], diff[i]);
    }

    ll ans = max(max(accum[N-1]-accum[0], accum[N-3]), accum[1]);
    for(ll oe = 1; oe < N-2; oe+=2){
        ans = max(ans, accum[1]+diff[oe]+eomax[oe+1]);
    }

    cerr << "Answer:" << endl;
    cout << ans << endl;

    return 0;
  }

}

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

void chmax(ll &a, const ll b) { if (a < b) a = b; return; }
const ll INF = 1ll<<60;

int main() {
    int n; cin >> n;
    vector<ll> a(n); for (int i = 0; i < n; i++) cin >> a[i];
    if (n % 2 == 0) {
        ll count = 0;
        for (int i = 0; i < n; i += 2) count += a[i];
        ll ans = count;
        for (int i = n-2; i >= 0; i -= 2) {
            count += a[i+1];
            count -= a[i];
            chmax(ans,count);
        }
        cout << ans << endl;
        return 0;
    }
    else {
        vector<vector<ll>> dp(n+2,vector<ll>(3,-INF));
        dp[0][0] = 0ll;
        for (int i = 1; i <= n+1; i++) {
            for (int j = 0; j < 3; j++) {
                if (i-2 >= 0) chmax(dp[i][j], dp[i-2][j] + a[i-2]);
            }
            for (int j = 1; j < 3; j++) {
                if (i-1 >= 0) chmax(dp[i][j], dp[i-1][j-1]);
            }
        }
        cout << dp[n+1][2] << endl;
        return 0;
    }
}


#include <cstdio>
#include <iostream>
#include <cmath>
#include <ctype.h>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <queue>
#include <utility>
#include <vector>
#include <set>
#include <iomanip>

using namespace std;

#define pi 3.141592653589793

int solve(int n, int p[])
{
	int result[101][101];
	for(int i = 0; i < n + 1; i++){
		for(int j = 0; j < n + 1; j++){
			if(i == j) result[i][j] = 0;
			else result[i][j] = 1000000;
		}
	}
	for(int i = 2; i < n + 1; i++){
		for(int j = 1; j < n - i + 2; j++){
			for(int k = j; k < j + i - 1; k++){
				result[j][j + i - 1] = min(result[j][j + i - 1], result[j][k] + result[k + 1][j + i - 1] + p[j - 1] * p[k] * p[j + i - 1]);
			}
		}
	}
	// i : 掛け合わせる行列の個数
	// j : 掛け合わせる行列のうち一番左のもの
	// k : 左から何番目で分けるか
	return result[1][n];
}

int main()
{
	int n;
	cin >> n;
	int p[101];
	for(int i = 1; i < n + 1; i++){
		cin >> p[i - 1] >> p[i];
	}
	cout << solve(n, p) << endl;
	return 0;
}

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

const int N = 100005;

int n, m, q, a[N], b[N];

void solve() {
	read(n), read(m), read(q);
	for (int i = 1; i <= n; ++i) {
		read(a[i]);
	}
	for (int i = 1; i <= m; ++i) {
		read(b[i]);
	}
	int ans = *std::min_element(a + 1, a + 1 + n) + *std::min_element(b + 1, b + 1 + m);
	for (int i = 1; i <= q; ++i) {
		int x, y, c;
		read(x), read(y), read(c);
		ans = std::min(ans, a[x] + b[y] - c);
	}
	print(ans);
}

int main() {
	int T = 1;
	// read(T);
	while (T--) {
		solve();
	}
}


#include<queue>
#include<stack>
#include<math.h>
#include<cmath>
#include<bitset>
#include<stdio.h>
#include<string>
#include<map>
#include<algorithm>
#include<vector>
#include<iostream>
#include<utility>
#include<functional>
#include<deque>
#include<list>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int main(){
  int i,k,x;
  cin >> k >> x;
  for(i=x-k+1;i<=k+x-1;i++){
    if(i==x-k+1){
      printf("%d",i);
    }
    else{
      printf(" %d",i);
    }
  }
  printf("\n");
  return 0;
}

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <bitset>
#include <string>
#include <cmath>
#include <complex>
#include <numeric>
#include <cassert>

#include <vector>
#include <array>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <utility>

#define PI 3.14159265358979323846
#define int64 long long
#define uint64 unsigned long long
#define coutfix(i) cout << fixed << setprecision(i)		//coutの浮動小数出力の桁数設定
using namespace std;

const int64 mod = 998244353;

int64 mpow(int64 mm, int64 xx)
{
	if(xx == 0)
	{
		return 1;
	}
	int64 tmp = mpow(mm, xx / 2);
	tmp *= tmp;
	tmp %= mod;
	if(xx % 2 == 1)
	{
		tmp *= mm;
		tmp %= mod;
	}
	return tmp;
}

int main()
{
	int64 kk, xx;
	cin >> kk >> xx;
	for(int64 ii = xx - kk + 1;ii <= xx + kk - 2;ii++)
	{
		cout << ii << ' ';
	}
	cout << (xx + kk - 1) << endl;
	return 0;
}


#include<iostream>
#include<math.h>
using namespace std;
int main()
{
	int n; cin >> n; cout << n / 3;

}

#include <bits/stdc++.h>
using namespace std;
int main()
{
   int n;
   cin>>n;
    if(n<3)
        cout<<0;
    else if (n%3==0)
        cout<<n/3;
    else if(n%3!=0){
        while(true){
            n++;
            if(n%3==0){
                cout<<n/3-1;
             break;
            }
        }
    }
   return 0;
   }


#include<stdio.h>
#include<iostream>
#include<string>
#include<memory>
#include<cmath>
#include<algorithm>
#include<vector>
int main(){
    int N;
    std::vector<int> vec;

    std::cin>>N;

    if(N==0){
        std::cout<<0<<std::endl;
        return 0;
    }

    while(N!=0){
        vec.emplace_back(abs(N%2));
        N-=abs(N%2);
        N/=-2;
    }

    for(int i=vec.size()-1;0<=i;i--) std::cout<<vec[i];
    std::cout<<std::endl;

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define fi first
#define se second
#define eb emplace_back
#define mt make_tuple
#define all(x) (x).begin(), (x).end()
#define MOD 1000000007

typedef long long ll;
typedef pair <int, int> ii;
typedef pair <ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef long double ld;

const ll INF=LLONG_MAX;
ll pow2[32];
vector<char>s(32,'0');
vll dp,dp2;

void init(){
	pow2[0]=1LL;
	for(int i=1; i<32; i++)
		pow2[i] = pow2[i-1]*2LL;
	for(int i=0; i<32; i+=2){
		if(dp.empty())dp.eb(pow2[i]);
		else dp.eb(pow2[i]+dp.back());
	}
	for(int i=1; i<32; i+=2){
		if(dp2.empty())dp2.eb(pow2[i]);
		else dp2.eb(pow2[i]+dp2.back());
	}
}

void solve(int x){
	if(x==0)return;
	else if(x<0){
		auto ptr = lower_bound(all(dp2),x*-1)-dp2.begin();
		int next = x+pow2[ptr*2+1];
		s[ptr*2+1]='1';
		solve(next);
	}else{
		auto ptr = lower_bound(all(dp),x)-dp.begin();
		int next = x-pow2[ptr*2];
		s[ptr*2]='1';
		solve(next);
	}
	return;
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);
    //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
	int x; cin >> x;
	init();
	if(x==0){
		cout << 0 << endl;
		return 0;
	}
	solve(x);
	reverse(all(s));
	bool st=0;
	for(auto ch:s){
		if(ch=='1')st=1;
		if(st)cout << ch;
	}
}

// READ & UNDERSTAND
// ll, int overflow, array bounds, memset(0)
// special cases (n=1?), n+1 (1-index)
// do smth instead of nothing & stay organized
// WRITE STUFF DOWN


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

int main() {
  ios::sync_with_stdio(false), cin.tie(0);
  int n;
  cin >> n;
  if (n == 1) {
    cout << "Hello World";
  } else {
    int a, b;
    cin >> a >> b;
    cout << a + b << '\n';
  }
  return 0;
}

#include<cstdio>
#include<iostream>
int main(){
    int nowpoint,wran[3]={0},kran[3]={0},wsum=0,ksum=0;
    for(int i=0;i<10;i++){
        scanf("%d",&nowpoint);
        if(wran[0]<nowpoint)
            wran[2]=wran[1],wran[1]=wran[0],wran[0]=nowpoint;
        else if(wran[1]<nowpoint)
            wran[2]=wran[1],wran[1]=nowpoint;
        else if(wran[2]<nowpoint)
            wran[2]=nowpoint;
    }
    for(int i=0;i<10;i++){
        scanf("%d",&nowpoint);
        if(kran[0]<nowpoint)
            kran[2]=kran[1],kran[1]=kran[0],kran[0]=nowpoint;
        else if(kran[1]<nowpoint)
            kran[2]=kran[1],kran[1]=nowpoint;
        else if(kran[2]<nowpoint)
            kran[2]=nowpoint;
    }
    for(int i=0;i<3;i++)
        wsum+=wran[i],ksum+=kran[i];
    printf("%d %d\n",wsum,ksum);
    return 0;
}


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

#define ll long long
#define ld long double
#define ar array

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define vt vector
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()

#define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>(b); i+=(s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define FOR(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define EACH(x, a) for (auto& x: a)

template<class A> void read(vt<A>& v);
template<class A, size_t S> void read(ar<A, S>& a);
template<class T> void read(T& x) {
	cin >> x;
}
void read(double& d) {
	string t;
	read(t);
	d=stod(t);
}
void read(long double& d) {
	string t;
	read(t);
	d=stold(t);
}
template<class H, class... T> void read(H& h, T&... t) {
	read(h);
	read(t...);
}
template<class A> void read(vt<A>& x) {
	EACH(a, x)
		read(a);
}
template<class A, size_t S> void read(array<A, S>& x) {
	EACH(a, x)
		read(a);
}

string to_string(char c) {
	return string(1, c);
}
string to_string(bool b) {
	return b?"true":"false";
}
string to_string(const char* s) {
	return string(s);
}
string to_string(string s) {
	return s;
}
string to_string(vt<bool> v) {
	string res;
	FOR(sz(v))
		res+=char('0'+v[i]);
	return res;
}

template<size_t S> string to_string(bitset<S> b) {
	string res;
	FOR(S)
		res+=char('0'+b[i]);
	return res;
}
template<class T> string to_string(T v) {
    bool f=1;
    string res;
    EACH(x, v) {
		if(!f)
			res+=' ';
		f=0;
		res+=to_string(x);
	}
    return res;
}

template<class A> void write(A x) {
	cout << to_string(x);
}
template<class H, class... T> void write(const H& h, const T&... t) {
	write(h);
	write(t...);
}
void print() {
	write("\n");
}
template<class H, class... T> void print(const H& h, const T&... t) {
	write(h);
	if(sizeof...(t))
		write(' ');
	print(t...);
}

void DBG() {
	cerr << "]" << endl;
}
template<class H, class... T> void DBG(H h, T... t) {
	cerr << to_string(h);
	if(sizeof...(t))
		cerr << ", ";
	DBG(t...);
}
#ifdef _DEBUG
#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
#define dbg(...) 0
#endif

template<class T> void offset(ll o, T& x) {
	x+=o;
}
template<class T> void offset(ll o, vt<T>& x) {
	EACH(a, x)
		offset(o, a);
}
template<class T, size_t S> void offset(ll o, ar<T, S>& x) {
	EACH(a, x)
		offset(o, a);
}

mt19937 mt_rng(chrono::steady_clock::now().time_since_epoch().count());
ll randint(ll a, ll b) {
	return uniform_int_distribution<ll>(a, b)(mt_rng);
}
const int d4i[4]={-1, 0, 1, 0}, d4j[4]={0, 1, 0, -1};
const int d8i[8]={-1, -1, 0, 1, 1, 1, 0, -1}, d8j[8]={0, 1, 1, 1, 0, -1, -1, -1};
ll mod=1e9+7;
const int N=1e6+5;
const ld PI=2*acos(0.0);

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

#define lcm(a,b) ((a)*(b))/(__gcd(a,b))

bool compare(array<int,2> a,array<int,2> b){
return a[0]<b[0];
}
void solve() {
int n,t; read(n,t);
vt<array<int,2> > td(n+1);
FOR(i,1,n+1) read(td[i][0],td[i][1]);
sort(++td.begin(),td.end(),compare);
int siz=(*--td.end())[0]+t+5;
vt<int> dp(siz,0);
vt<int> pre(siz,0);
FOR(i,1,n+1){
FOR(j,1,siz){
if(j-td[i][0]<0||j-td[i][0]>=t) { dp[j]=pre[j];}
else{ dp[j]=max(pre[j],pre[j-td[i][0]]+td[i][1]);}
}
FOR(j,1,siz){ pre[j]=dp[j]; dp[j]=0; }
//dbg(i,pre);
}
print(*max_element(all(pre)));
}

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

#include<bits/stdc++.h>
using namespace std;
//#pragma region atcoder
/*#include <atcoder/dsu>
using namespace atcoder;*/
//using mint = modint998244353;
//These are for segment tree
/*int op(int a, int b){return max(a, b);}
int e(){return -1;}
bool f(int v){ return v < target;}
*/
#pragma endregion
#pragma region macros
using ll = long long;
using vi = vector<int>;
using vs = vector<string>;
using vl = vector<ll>;
using vb = vector<bool>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<ll>>;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rrep(i, n) for(int i = n - 1; i >= 0; i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)(x).size())
#pragma endregion
#pragma region debug for var, v, vv
#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){cout << endl;int cnt = 0;for(const auto& v : vv){cout << cnt << "th : "; view(v); cnt++;} cout << endl;}
#pragma endregion

const ll mod = 1000000007;
const int inf = 1001001001;
const ll INF = 1001001001001001001;

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; }
ll modpow(ll a, ll p){ll ret = 1; while(p){if(p & 1){ret = ret * a % mod;} a = a * a % mod; p >>= 1;} return ret;}

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

/*-----------------------------------------------------------------------------------------------------*/
int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n, t; cin >> n >> t;
	vector<pair<int, int>> p(n);
	rep(i,n) cin >> p[i].first >> p[i].second;
	sort(all(p));
	vvi dp(n + 1, vi(t));
	rep(i,n){
		rep(j,t){
			chmax(dp[i + 1][j], dp[i][j]);
			if(j - p[i].first >= 0) chmax(dp[i + 1][j], dp[i][j - p[i].first] + p[i].second);
		}
	}
	int ans = 0;
	rep(i,n){
		ans = max(ans, dp[i][t - 1] + p[i].second);
	}
	cout << ans << endl;
}


#include <bits/stdc++.h>

using namespace std;

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

#define FOR(i, n, m) for(ll (i)=(m);(i)<(n);++(i))
#define REP(i, n) FOR(i,n,0)
#define OF64 std::setprecision(10)

const ll MOD = 1000000007;
const ll INF = (ll) 1e15;
ll N, Q;
string S;

ll solve(ll k) {
    ll ret = 0;
    ll D = 0;
    ll M = 0;
    ll C = 0;
    REP(i, N) {
        if (i - k >= 0) {
            ll index = i - k;
            if (S[index] == 'D') {
                D--;
                C -= M;
            }
            else if (S[index] == 'M') {
                M--;
            }
        }

        if (S[i] == 'C')
            ret += C;
        else if (S[i] == 'M') {
            M++;
            C += D;
        }
        else if (S[i] == 'D')
            D++;
    }
    return ret;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> N >> S >> Q;
    REP(i, Q) {
        ll k;
        cin >> k;
        cout << solve(k) << endl;
    }
    return 0;
}

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <queue>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
const int INF = 1<<30;

int main() {
  int n;
  while(cin>>n,n) {
    REP(i,n) {
      int m,e,j;
      cin >> m >> e >> j;
      char c;
      if (m == 100 || e == 100 || j == 100)
        c = 'A';
      else if (m + e >= 180)
        c = 'A';
      else if (m + e + j >= 240)
        c = 'A';
      else if (m + e + j >= 210)
        c = 'B';
      else if (m + e + j >= 150 && (m >= 80 || e >= 80))
        c = 'B';
      else
        c = 'C';
      cout << c << endl;
    }
  }
}


////////////////////////// Author
////////////////////////// Nasim Hossain Rabbi
////////////////////////// JU-CSE28
////////////////////////// CF - imnasim3.1415
////////////////////////// UVA - imnasim3.1415
////////////////////////// Mail - imnasim3.1415@gmail.com
#include<bits/stdc++.h>
using namespace std;
#define E end()
#define B begin()
#define sz size()
#define EM empty()
#define fi first
#define se second
#define cl clear()
#define sqr(a) (a*a)
#define mk make_pair
#define po pop()
#define pu push
#define pb push_back
#define pf push_front
#define pob pop_back()
#define pof pop_front()
string en="\n";
string sp=" ";
string t="hello";
string Y="YES\n";
string N="NO\n";
#define rep(i,n) for(i=0;i<n;i++)
#define Rep(i,n) for(i=1;i<=n;i++)
#define per(i,n) for(i=n-1;i>=0;i--)
#define peR(i,n) for(i=n;i>0;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define all(cont) cont.begin(),cont.end()
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL)
#define pi 3.1415926535897932384626433832795
#define vi vector<long long>
#define vs  vector<string>
#define MX LLONG_MAX
#define MN LLONG_MIN
#define MOD 1000000007
#define vp(vi,x) cin>>x; vi.pb(x);
#define bsearch(a,x) binary_search(all(a),x)
#define LB(a,x) (lower_bound(all(a),x)-a.B)
#define UB(a,x) (upper_bound(all(a),x)-a.B)
typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;
bool isprm(LL a){if(a==1)return false; for(LL i=2;i*i<=a;i++){if(a%i==0)return false;}return true;}
bool palin(string a){for(int i=0;i<a.sz;i++){if(a.at(i)!=a.at(a.sz-i-1))return 0;} return 1;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
int toInt(string s){int sm;stringstream ss(s);ss>>sm;return sm;}
LL ceil2(LL a,LL b){LL c=a/b; if(a%b)c++; return c; }
LL bpow(LL a,LL b){if(b==0)return 1;LL r=bpow(a,b/2);if(b%2)return r*r*a;else return r*r;}
LL binpow(LL a,LL b){LL r=1;while(b>0){if(b&1)r=r*a;a=a*a;b>>=1;}return r;}
LL binpow(LL a,LL b,LL m){a%=m;LL r=1;while(b>0){if(b&1) r=r*a%m;a=a*a%m; b>>=1;}return r;}
template<typename T>inline T gcd(T a,T b){if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);}
template<typename T>inline T lcm(T a,T b) {if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));}
int main()
{
//    fast;
    LL i,j,k,n,m,l,s=0,x,y,tc=1,p,q,a,b,c=0;
    bool f=0,ff=0;string st,s1,s2,s3; char ch;
    while(cin>>n>>m)
    {
        a=b=0;
        bool ar[n+5];
        rep(i,n+5)ar[i]=0;
        map<LL,LL>mp;
        while(m--)
        {
            cin>>p>>st;
            if(ar[p])continue;
            if(st=="AC") a++,ar[p]=1;
            else mp[p]++;
        }
        for(auto it=mp.B;it!=mp.E;it++)
        {
            if(ar[it->fi])b+=it->se;
        }
        cout<<a<<sp<<b<<en;
    }
    return 0;
}

#include <algorithm>
#include <bitset>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stdio.h>
#include <string>
#include <vector>

#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
using LP = pair<ll, ll>;
const double PI = 3.1415926535897932;

int main()
{
	int N, M;
	cin >> N >> M;
	vector<string> S(M);
	vector<int> P(M);
	rep(i, M) {
		cin >> P[i] >> S[i];
		P[i]--;
	}
	vector<int> Ans(N, 0);

	int penalty = 0;
	int ac = 0;
	for (int i = 0; i < M; ++i) {
		if (S[i] ==  "AC" && Ans[P[i]] <= 0) {
			penalty += Ans[P[i]] * -1;
			Ans[P[i]] = 1;
			ac++;
		}
		else {
			if (Ans[P[i]] <= 0) {
				Ans[P[i]]--;
			}
		}
	}

	cout << ac << " " << penalty << endl;
	return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstring>
#define _GLIBCXX_DEBUG

#include <iomanip>
using namespace std;

template<typename T> vector<T> range(T begin, T end, T stride = 1) {
    vector<T> vec;
    for (T i = begin; i < end; i += stride) {
        vec.push_back(i);
    }
    return vec;
}

template<typename T> T factorial(T in) {
    long long ans = 1;
    for (int i=2; i < in + 1; ++i) ans *= i;
    return ans;
}

int main() {
    int n; cin >> n;
    vector<int> v = range(0, n);
    vector<int> x(n), y(n);
    for (int i=0; i < n; ++i) cin >> x[i] >> y[i];
    double sum = 0;
    do {
        for (int i=0; i<n-1; i++) {
            sum += sqrt((x[v[i+1]] - x[v[i]]) * (x[v[i+1]] - x[v[i]]) + (y[v[i+1]] - y[v[i]]) * (y[v[i+1]] - y[v[i]]));
        }
    } while(next_permutation(v.begin(), v.end()));
    cout << fixed << setprecision(15) << sum / factorial(n) << endl;
}

#include <bits/stdc++.h>
using namespace std;
// type alias
typedef long long LL;
typedef pair<int,int> II;
typedef tuple<int,int,int> III;
typedef vector<int> VI;
typedef vector<string> VS;
typedef unordered_map<int,int> MAPII;
typedef unordered_set<int> SETI;
template<class T> using VV=vector<vector<T>>;
// minmax
template<class T> inline T SMIN(T& a, const T b) { return a=(a>b)?b:a; }
template<class T> inline T SMAX(T& a, const T b) { return a=(a<b)?b:a; }
// repetition
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n)  for(int i=0;i<=(n);++i)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  for(int i=0;i<(n);++i)
#define FORR(x,arr) for(auto& x:arr)
#define SZ(a) int((a).size())
// collection
#define ALL(c) (c).begin(),(c).end()
// DP
#define MINUS(dp) memset(dp, -1, sizeof(dp))
#define ZERO(dp) memset(dp, 0, sizeof(dp))
// stdout
#define println(args...) fprintf(stdout, ##args),putchar('\n');
// debug cerr
template<class Iter> void __kumaerrc(Iter begin, Iter end) { for(; begin!=end; ++begin) { cerr<<*begin<<','; } cerr<<endl; }
void __kumaerr(istream_iterator<string> it) { (void)it; cerr<<endl; }
template<typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr<<*it<<"="<<a<<", ",__kumaerr(++it, args...); }
template<typename S, typename T> std::ostream& operator<<(std::ostream& _os, const std::pair<S,T>& _p) { return _os<<"{"<<_p.first<<','<<_p.second<<"}"; }
#define __KUMATRACE__ true
#ifdef __KUMATRACE__
#define dump(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); __kumaerr(_it, args); }
#define dumpc(ar) { cerr<<#ar<<": "; FORR(x,(ar)) { cerr << x << ','; } cerr << endl; }
#define dumpC(beg,end) { cerr<<"~"<<#end<<": "; __kumaerrc(beg,end); }
#else
#define dump(args...)
#define dumpc(ar)
#define dumpC(beg,end)
#endif

// $ cp-batch VotingJudges | diff VotingJudges.out -
// $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address VotingJudges.cpp && ./a.out

/*

 6/28/2020

 9:50-

 */

const int MAX_N=1e6+1;
LL A[MAX_N],M;
int N,V,P;

bool ok(int m) {
  vector<LL> as(A,A+N);
  int v=0;
  as[m]+=M,++v;
  REP(i,P-1) if(v<V) as[i]+=M,++v;
  int i=N-1;
  for(; i>=0&&v<V&&as[i]<=as[m]-M; --i) {
    LL x=min(as[m]-as[i],(LL)M);
    if(x>0) as[i]+=x,++v;
  }
  LL rem=M*(V-v);
  //dump(p,rem,i,as[P-1],as[p]);
  //dumpc(as);
  while(rem>0&&i>P-2) {
    LL x=min(as[m]-as[i],rem);
    rem-=x,as[i]+=x;
    --i;
  }
  if(rem>0) return false;
  else return as[m]>=as[P-1];
}
void solve() {
  sort(A,A+N),reverse(A,A+N);
  //dumpC(A,A+N);
  int good=P-1,bad=N;
  while(abs(good-bad)>1) {
    int mid=(good+bad)/2;
    bool res=ok(mid);
    //dump(mid,res);
    (res?good:bad)=mid;
  }
  cout<<good+1<<endl;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout<<setprecision(12)<<fixed;

  cin>>N>>M>>V>>P;
  REP(i,N) cin>>A[i];
  solve();

  return 0;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<deque>
#include<map>
#include<unordered_map>
#include<set>
#include<cmath>
#include<climits>
#include<random>
using namespace std;

#define pb push_back
#define ff first
#define ss second
#define endl '\n'
#define fast ios::sync_with_stdio(false); cin.tie(NULL);
const double eps = 1e-6;

/////////////////////////////////////////////

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

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

////////////////////////////////

#define int long long

void solve(){

	int n;
	cin>>n;
	int a[n][n];

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

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

	int nn = (1<<n);
	int dp[nn];
	memset(dp , 0 , sizeof dp);
	for(int i = 1 ; i <= nn ; ++i){

		vector<int> tmp;
		for(int j = 0 ; j < n ; ++j){

			if((1<<j)&i)
				tmp.pb(j);
		}

		for(int k = 0 ; k < tmp.size() ; ++k)
			for(int j = k + 1 ; j < tmp.size() ; ++j){

				dp[i] += a[tmp[k]][tmp[j]];
			}
	}

	for(int mask = 1 ; mask < nn ; ++mask){

		for(int i = mask ; i > 0 ; i= mask&(i-1)){

			dp[mask] = max(dp[mask] , dp[i] + dp[i^mask]);
		}
	}

	cout<<dp[nn-1]<<endl;
}

signed main(){

    fast;
    int t = 1;
    //cin>>t;
   	for(int i = 1 ; i <= t ; ++i){

   		solve();
   	}
}

#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>;
const int MAX = 100000;
const int INF = 1e9;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,-1,0,1};
#define PI 3.14159265358979323846264338327950L
#define MOD 1000000007
//setprecision(15)
ll mod_pow(ll x, ll n, ll mod) {
	ll res = 1;
	while (n > 0) {
		if (n & 1) res = res * x % mod;
		x = x * x % mod;
		n >>= 1;
	}
	return res;
}
#define MAX_N 15
int A[MAX_N+1][MAX_N+1];
int main() {
	memset(A, -1, sizeof(A));
	int N; cin >> N;
	for (int i = 1; i <= N; i++) {
		int cnt; cin >> cnt;
		rep(j, cnt) {
			int tmp; cin >> tmp;
			cin >> A[i][tmp];
		}
	}
	int p = mod_pow(2, N, MOD);
	int ans = 0;
	for (int i = 1; i < p; i++) {
		int NG_flg = 0;
		for (int j = 0; (1 << j) < p; j++ ) {
			if (NG_flg == 1) break;
			if (!(i & (1 << j))) continue;
			for (int k = 1; k <= N; k++ ) {
				if (A[j+1][k] == -1) continue;
				if ( (A[j+1][k] == 1 && (i & (1 << (k-1))) == 0) ||
				     (A[j+1][k] == 0 && (i & (1 << (k-1))) > 0) ) {
					NG_flg = 1; break;
				}
			}
		}
		if (NG_flg == 0) {
			int cnt = 0;
			rep(j, 16) {
				if (i & (1 << j)) cnt++;
			}
			ans = max(ans, cnt);
		}
	}
	cout << ans << endl;
}


//---------------------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <math.h>
#include <sstream>
#include <numeric>
#include <cctype>
#include <bitset>
#include <cassert>
#include<algorithm>
//---------------------------------------------------------------
#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 rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
#define SIZE 100005
#define INF 1e18
#define all(x) x.begin(),x.end()
#define fi first
#define se second
#define vec vector
using pint = pair<int,int>;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
//---------------------------------------------------------------
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; }
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const double pi = acos(-1);
//---------------------------------------------------------------

//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

vector<int> Eratosthenes( const int N )
{
    vector<bool> is_prime( N + 1 );
    for( int i = 0; i <= N; i++ )
    {
        is_prime[ i ] = true;
    }
    vector<int> P;
    for( int i = 2; i <= N; i++ )
    {
        if( is_prime[ i ] )
        {
            for( int j = 2 * i; j <= N; j += i )
            {
                is_prime[ j ] = false;
            }
            P.emplace_back( i );
        }
    }
    return P;
}

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

    ll n;
    cin>>n;

    auto b = Eratosthenes(55555);

    int cnt=0;
    for(auto a : b){
        if(a%5==1){
            cout<<a<<' ';
            cnt++;
            if(cnt==n){
                break;
            }
        }
    }

    return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main(){
  string key;
  while(getline(cin,key)){
    if(key.size() > 80){
      break;
    }
    for(int j=0; j<26; j++){
      for(int i=0; i<key.size(); i++){
	if(key[i] >= 'a' && key[i] <= 'z'){
	  if(key[i] == 'z')
	    key[i] = 'a';
	  else
	    key[i] += 1;
	}
      }
      if(key.find("the") != string::npos || key.find("this") != string::npos || key.find("that") != string::npos){
	cout << key << 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 k;
    cin >> k;
    vector<pair<int, int> > in(k);
    rep(i, k) cin >> in[i].first >> in[i].second;

    vector<int> p(8);
    rep(i, 8) p[i] = i;

    do{
        bool check = true;
        rep(i, k){
            if(p[in[i].first] != in[i].second){
                check = false;
                break;
            }
        }
        if(!check) continue;

        bool flag = true;
        rep(i, 7){
            // (1, 1)方向チェック
            for(int j = i + 1; j < 8; ++j){
                int r_dif = j - i;
                int l_dif = p[i] + r_dif;
                if(l_dif == p[j]) flag = false;
            }
            // (1, -1)方向チェック
            for(int j = i + 1; j < 8; ++j){
                int r_dif = j - i;
                int l_dif = p[i] - r_dif;
                if(l_dif == p[j]) flag = false;
            }
        }
        if(flag) break;
    }while(next_permutation(p.begin(), p.end()));

    rep(i, 8){
        rep(j, 8){
            if(p[i] == j){
                cout << "Q";
            }else{
                cout << ".";
            }
        }
        cout << endl;
    }

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

bool flg;

void init(char field[8][8],bool can[8][8]){
  flg = false;
  for(int i = 0 ; i < 8 ; i++){
    for(int j = 0 ; j < 8 ; j++){
      field[i][j] = '.';
      can[i][j] = true;
    }
  }
}

bool inField(int y,int x){
  return 0 <= y && y < 8 && 0 <= x && x < 8;
}

void putQ(int r,int c,bool can[8][8]){
  const int dx[4] = {-1,1,1,-1};
  const int dy[4] = {-1,-1,1,1};
  for(int i = 0 ; i < 8 ; i++){
    can[r][i] = can[i][c] = false;
  }
  for(int i = 0 ; i < 4 ; i++){
    int x = c, y = r;
    while(inField(y,x)){
      can[y][x] = false;
      x += dx[i]; y += dy[i];
    }
  }
}

void print(char field[8][8]){
  for(int i = 0 ; i < 8 ; i++){
    for(int j = 0 ; j < 8 ; j++){
      cout << field[i][j];
    }
    cout << endl;
  }
}

void copy(bool a[8][8],bool b[8][8]){
  for(int i = 0 ; i < 8 ; i++){
    for(int j = 0 ; j < 8 ; j++){
      a[i][j] = b[i][j];
    }
  }
}

void solve(int now,int S,bool can[8][8],char field[8][8]){
  if(now == 8){
    print(field);
    flg = true;
    return;
  }
  if((S >> now) & 1){
    solve(now+1,S,can,field);
  }else{
    bool tmp[8][8];
    for(int i = 0 ; i < 8 ; i++){
      if(can[now][i]){
    copy(tmp,can);
    field[now][i] = 'Q';
    putQ(now,i,can);
    solve(now+1,S,can,field);
    if(flg) return;
    copy(can,tmp);
    field[now][i] = '.';
      }
    }
  }
}

int main(){
  int N,r,c,S = 0;
  bool can[8][8];
  char field[8][8];

  init(field,can);

  cin >> N;
  for(int i = 0 ; i < N ; i++){
    cin >> r >> c;
    S |= 1<<r;
    field[r][c] = 'Q';
    putQ(r,c,can);
  }
  solve(0,S,can,field);
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define lp(i,n) for(int i=0;i<n;i++)
int memo[10001],color[10001];
stack<int> numb;
vector<int> connect[10001],rconnect[10001];

void dfs(int i){
  if(memo[i]!=0) return;
  memo[i]=1;
  lp(j,connect[i].size()){
    dfs(connect[i][j]);
  }
  numb.push(i);
  return;
}

void rdfs(int i,int j){
  if(memo[i]!=1) return;
  memo[i]=2;
  color[i]=j;
  lp(k,rconnect[i].size()){
    rdfs(rconnect[i][k],j);
  }
  return;
}

int main(){
  int v,e;
  cin>>v>>e;
  lp(i,e){
    int a,b;
    cin>>a>>b;
    connect[a].push_back(b);
    rconnect[b].push_back(a);
  }
  for(int i=0;i<v;i++){
    if(memo[i]==0) {
      dfs(i);
    }
  }
  int j=0;
  for(int i=0;i<v;i++){
    int x=numb.top();
    numb.pop();
    if(memo[x]==1) {
      rdfs(x,j);
      j++;
    }
  }
  int q;
  cin>>q;
  lp(i,q){
    int a,b;
    cin>>a>>b;
    if(color[a]==color[b]) cout<<"1"<<endl;
    else cout<<"0"<<endl;
  }

  return 0;
}

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

struct edge
{
    int to;
    ll cost;
};
vector<vector<edge>> tree(100010);
vector<ll> depth(100010);

void dfs(int v, int p, ll d)
{ //vからの最短経路、現在地のいっこまえ、はじめからの距離
    depth[v] = d;
    for (auto &e : tree[v])
    {
        if (e.to == p)
            continue;
        dfs(e.to, v, d + e.cost);
    }
}

int main()
{
    int n;
    cin >> n;
    rep(i, n - 1)
    {
        int a, b, c;
        cin >> a >> b >> c;
        a--;
        b--;
        tree[a].push_back({b, c});
        tree[b].push_back({a, c});
    }

    int q, k;
    cin >> q >> k;
    k--;

    dfs(k, -1, 0);
    rep(i, q)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        cout << depth[x] + depth[y] << endl;
    }
}


// https://atcoder.jp/contests/agc005/tasks/agc005_a
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <set>
#include <unordered_set>
#include <bitset>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define REP(i, n) for(size_t i = 0; i < (n); ++i)

int main()
{
    string X;
    cin >> X;
    int N = X.size();

    stack<char> st;
    for (int i = 0; i < N; ++i)
    {
        // 見ている文字とスタックの先頭に着目する
        if ('S' == X[i])
        {
            st.push('S');
        }
        else // 'T' == X[i]
        {
            if (st.empty())
            {
                st.push('T');
                continue;
            }

            char c = st.top();
            if (c == 'T')
            {
                st.push('T');
            }
            else // c == 'S'
            {
                st.pop();
            }
        }
    }
    cout << st.size() << endl;
    return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

int main()
{
  ll n; cin >> n;
  ll a = n/500;
  n %= 500;
  cout << (a*1000) + int(n/5)*5 << endl;
  return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main()
{
	long long mod=(1e+9)+7;
	long long n,m;
	cin>>n>>m;
	static long long sum_x,sum_y;
	vector<long long> x(n+10),y(m+10);
	for(ll i=1;i<=n;i++) cin>>x[i];
	for(ll i=1;i<=m;i++) cin>>y[i];
	for(ll xx=1;xx<=n;xx++){
		sum_x+=(2*xx-n-1)*x[xx];
		sum_x%=mod;
	}
	for(ll yy=1;yy<=m;yy++){
		sum_y+=(2*yy-m-1)*y[yy];
		sum_y%=mod;
	}
	cout<<(sum_x*sum_y)%mod<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define F first
#define S second
const int mod = 1e9 + 7, A = 5e5 + 2;

int main() {
    ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n, x;
    cin >> n >> x;
    ll a[n];
    for (int i = 0; i < n; i++) cin >> a[i];
    ll sum = 0;
    for (int i = 0; i <= x; i++) {
        for (int j = 0; i + j <= min(n, x); j++) {
            priority_queue<ll, vector<ll>, greater<ll>> pq;
            for (int k = 0; k < i; k++)
                pq.push(a[k]);
            for (int k = n - 1, c = 0; c < j; c++, k--)
                pq.push(a[k]);
            for (int k = i + j; k < x; k++) {
                if (!pq.empty() && pq.top() < 0) pq.pop();
            }
            ll val = 0;
            while(!pq.empty()) val += pq.top(), pq.pop();
            sum = max(sum, val);
        }
    }
    cout << sum;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2005;
const int ha=1000000007;
int jc[maxn*maxn],ni[maxn*maxn];
int n,k,f[maxn][maxn];

inline int add(int x,int y){
    x+=y;
    return x>=ha?x-ha:x;
}

inline int ksm(int x,int y){
    int an=1;
    for(;y;y>>=1,x=x*(ll)x%ha) if(y&1) an=an*(ll)x%ha;
    return an;
}

inline void init(){
    jc[0]=1;
    for(int i=1;i<=4004000;i++) jc[i]=jc[i-1]*(ll)i%ha;
    ni[4004000]=ksm(jc[4004000],ha-2);
    for(int i=4004000;i;i--) ni[i-1]=ni[i]*(ll)i%ha;
}

inline int getC(int x,int y){
    return jc[x]*(ll)ni[y]%ha*(ll)ni[x-y]%ha;
}

inline void dp(){
    f[0][0]=1;
    for(int i=0;i<=n;i++)
        for(int j=i;j>=0;j--) if(f[i][j]){
            f[i+1][j+1]=add(f[i+1][j+1],f[i][j]*(ll)(n-i)%ha*(ll)getC(k*(i+1)-j-2,k-2)%ha);
            if(j) f[i][j-1]=add(f[i][j-1],f[i][j]);
        }

    /*
    for(int i=0;i<=n;i++){
        for(int j=0;j<=i;j++) printf("%d ",f[i][j]);
        puts("");
    }
    */
}

int main(){
    init();
    scanf("%d%d",&n,&k);
    if(k==1) puts("1");
    else{
        dp();
        printf("%d\n",f[n][0]);
    }
    return 0;
}
/*
仅有一个序列中的每一个白球都能在其后方匹配到一个是其颜色里出现第一次的彩球，
这个序列才合法。

    从后向前dp,

    f[i][j] 表示 已经完整出现过 i种颜色的球，
    并且还剩j种颜色的球没有被匹配的方案数。

    考虑加入一种新球的话:
    f[i+1][j+1] += f[i][j] * (n-i) * C(k*(i+1)-j-2,k-2)

    考虑加入一种白球的话:
    f[i][j-1] += f[i][j]

    初始化 f[0][0] = 1
*/

#include <stdio.h>

#include <string.h>

int x;

char y[101];

int main(){

	scanf("%d",&x);	scanf("%s",&y);

	int len = strlen(y);

	if(len<=x){

		printf("%s\n",y);

		return 0;

	}

	else{

		for(int i=x; i<len; i++){

			y[i]='\0';

		}

		for(int i=x; i<x+3; i++){

			y[i]='.';

		}

		printf("%s\n",y);

		return 0;

	}

}


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

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

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

const int INF = 1001001001;
const int MOD = 1000000007;
const double PI=acos(-1);

char next_char(char now, char pre, string &s, int k) {
    if (s[k]=='o') {
        if (now=='S') return pre;
        else if (pre=='W') return 'S';
        else return 'W';
    }
    else {
        if (now=='W') return pre;
        else if (pre=='W') return 'S';
        else return 'W';
    }
}

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

    map<int,string> mp;
    mp[0] = "S";
    mp[1] = "W";

    rep(i,2) rep(j,2) {
        string ans = mp[i] + mp[j];
        rep(k,N-1) {
            char now = ans[k+1];
            char pre = ans[k];
            char next = next_char(now,pre,s,k+1);
            if (k==N-2) {
                if (next==ans[0]) {
                    pre = now;
                    now = ans[0];
                    next = next_char(now,pre,s,0);
                    if (next==ans[1]) {
                        cout << ans << endl;

                        return 0;
                    }
                }
            }
            else {
                ans += next;
            }
        }
    }
    cout << -1 << endl;
    return 0;
}


#include <iostream>
using namespace std;
int main(){
      int n,count=0;
      cin>> n;
      int num[n];
      for(int i= 0;i<n;i++)
            cin>>num[i];
      bool flag=true;
      while(flag){
            flag=false;
            for(int j = n-1 ; j>0;j--){
                  if(num[j]<num[j-1]){
                        swap(num[j],num[j-1]);
                        flag = true;
                        count++;
                  }
            }
      }
      for(int i= 0;i<n-1;i++)
            cout<<num[i]<<" ";
      cout<<num[n-1]<<endl<<count<<endl;
}

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <complex>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <iostream>
#include <map>
#include <set>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define INF 2000000000
#define sz(x) ((int)(x).size())
#define fi first
#define sec second
#define SORT(x) sort((x).begin(),(x).end())
#define all(x) (x).begin(),(x).end()
#define EQ(a,b) (abs((a)-(b))<eps)
const int MAX=100000;
const int geta=100;
struct BIT
{
	int bit[MAX+1];
	void add(int i,int x)
	{
		while(i<=MAX)
		{
			bit[i]+=x;
			i+=i&-i;
		}
	}
	int sum(int i)
	{
		int res=0;
		while(i>0)
		{
			res+=bit[i];
			i-=i&-i;
		}
		return res;
	}
};
BIT bit;
int N,a[105];
int main()
{
	scanf("%d",&N);
	for(int i=0;i<N;i++)
	{
		scanf("%d",&a[i]);
		a[i]+=geta;
	}
	int ans=0;
	for(int i=0;i<N;i++)
	{
		ans+=bit.sum(a[i]);
		bit.add(a[i],1);
	}
	sort(a,a+N);
	for(int i=0;i<N;i++)printf("%d%c",a[i]-geta,(i==N-1)?'\n':' ');
	printf("%d\n",N*(N-1)/2-ans);
	return 0;
}


#include<iostream>
using namespace std;

int main()
{
	int N;
	int M;
	int x[20];
	int y[20];
	char d;
	int l;

	while (cin >> N && N != 0)
	{
		int flag[21][21] = {};
		int initX = 10;
		int initY = 10;
		int cnt = 0;

		for (int i = 0; i < N; i++)
		{
			cin >> x[i];
			cin >> y[i];
			flag[y[i]][x[i]] = 1;
		}

		cin >> M;

		for (int i = 0; i < M; i++)
		{
			cin >> d;
			cin >> l;
			int dx = 0;
			int dy = 0;

			for (int k = 0; k <= l; k++)
			{
				if (d == 'S' || d == 'W')
				{
					if (d == 'S')
					{
						for (int j = 0; j < N; j++)
						{
							if (x[j] == initX && y[j] == initY - k && flag[y[j]][x[j]] == 1)
							{
								cnt++;
								flag[y[j]][x[j]] = 0;
							}
						}
					}
					else
					{
						for (int j = 0; j < N; j++)
						{
							if (x[j] == initX - k && y[j] == initY && flag[y[j]][x[j]] == 1)
							{
								cnt++;
								flag[y[j]][x[j]] = 0;
							}
						}
					}
				}
				else
				{
					if (d == 'N')
					{
						for (int j = 0; j < N; j++)
						{
							if (x[j] == initX && y[j] == initY + k && flag[y[j]][x[j]] == 1)
							{
								cnt++;
								flag[y[j]][x[j]] = 0;
							}
						}
					}
					else
					{
						for (int j = 0; j < N; j++)
						{
							if (x[j] == initX + k && y[j] == initY && flag[y[j]][x[j]] == 1)
							{
								cnt++;
								flag[y[j]][x[j]] = 0;
							}
						}
					}
				}
			}
			if (d == 'S')
			{
				dy = -l;
			}
			else if (d == 'N')
			{
				dy = l;
			}
			else if (d == 'W')
			{
				dx = -l;
			}
			else
			{
				dx = l;
			}

			initX += dx;
			initY += dy;
		}
		if (cnt == N)
		{
			cout << "Yes" << endl;
		}
		else
		{
			cout << "No" << endl;
		}

	}
	return 0;
}

#include<iostream>
#include<vector>

using namespace std;
const int inf=1e8;

int main(){

    while(1){
        int n, m;
        cin>> n>> m;
        if(n==0&&m==0) break;
        int a[m], b[m];
        for(int i=0; i<m; i++){
            cin>> a[i]>> b[i];
            a[i]--; b[i]--;
        }

        int mtrx[n][n];
        fill(mtrx[0], mtrx[n], inf);
        for(int i=0; i<m; i++){
            mtrx[a[i]][b[i]]=mtrx[b[i]][a[i]]=1;
        }

        for(int k=0; k<n; k++)
            for(int i=0; i<n; i++)
                for(int j=0; j<n; j++)
                    mtrx[i][j]=min(mtrx[i][j], mtrx[i][k]+mtrx[k][j]);

        int ans=0;
        for(int i=1; i<n; i++){
            if(mtrx[0][i]==2||mtrx[0][i]==1) ans++;
        }

        cout<< ans<< endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL_DEBUG
  #include "LOCAL_DEBUG.hpp"
#endif
#define int long long
const int MOD = 1e9 + 7;

template<class T> vector<T> make_vec(size_t a) { return vector<T>(a); }
template<class T, class... Ts> auto make_vec(size_t a, Ts... ts) {
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}
template<class T, class V>
typename enable_if<is_class<T>::value == 0>::type fill(T &t, const V &v) {
    t = v;
}
template<class T, class V>
typename enable_if<is_class<T>::value != 0>::type fill(T &t, const V &v){
    for (auto &e : t) fill(e, v);
}
// auto v = make_vec<int>(h, w);
// fill(v, 0);

signed main(){

  int n, x; cin >> n >> x;
  vector<int> s(n);
  for(int i = 0; i < n; i++) cin >> s[i];
  sort(s.begin(),s.end());

  auto dp = make_vec<int>(n+1, x+1);
  for(int i = 0; i <= x; i++){
    dp[0][i] = i;
  }
  for(int i = 0; i < n; i++){
    for(int j = 0; j <= x; j++){
      dp[i+1][j] += dp[i][j % s[i]]; dp[i+1][j] %= MOD;
      dp[i+1][j] += dp[i][j] * i; dp[i+1][j] %= MOD;
    }
  }
  cout << dp[n][x] << endl;

  return 0;
}

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

#define DEBUG 0

#if DEBUG
  #define DLOG(...) fprintf(stderr, __VA_ARGS__)
#else
  #define DLOG(...)
#endif

void debug(auto f) {
#if DEBUG
  f();
#endif
}

ll mPrime = int(1e9) + 7;
ll bN, bX;
vector<ll> bS;
vector<ll> facts;
vector<ll> invFacts;
vector<int> tbl;
vector<int> low;  // low[y] == #{ i | s[i] <= y }

ll mAdd(ll x, ll y) {
  ll z = x + y;
  if (z < mPrime)  return z;
  else             return (z - mPrime);
}

ll mSub(ll x, ll y) {
  ll z = x - y;
  if (z >= 0)  return z;
  else         return (z + mPrime);
}

ll mMul(ll x, ll y) {
  return (x * y) % mPrime;
}

ll eGCD(ll a, ll b, ll& s, ll& t) {
  if (a == 0) {
    s = 0;
    t = 1;
    return b;
  }
  ll u;
  ll g = eGCD(b % a, a, t, u);
  s = u - (b / a) * t;
  return g;
}

ll mInv(ll x) {
  ll s, t;
  eGCD(x, mPrime, s, t);
  return s < 0 ? s + mPrime : s;
}

ll tight(ll);

ll loose(ll y, ll len) {
  ll result = mMul(tight(y), mMul(facts.at(len), invFacts.at(low.at(y))));
  DLOG("loose(%lld, %lld) = %lld\n", y, len, result);
  return result;
}

ll tight(ll y) {
  if (tbl.at(y) >= 0)  return tbl.at(y);
  ll len = low.at(y);
  if (len == 0)  return y;
  ll result = 0;
  for (ll i = 0; i < len; i++) {
    ll z = y % bS.at(i);
    result = mAdd(result, loose(z, len-1));
  }
  tbl.at(y) = result;
  DLOG("tight(%lld) = %lld\n", y, result);
  return result;
}

int main() {
  cin >> bN >> bX;
  bS.resize(bN);
  for (ll i = 0; i < bN; i++) {
    cin >> bS.at(i);
  }
  facts.resize(bN+1);
  invFacts.resize(bN+1);
  facts.at(0) = invFacts.at(0) = 1;
  for (ll i = 1; i <= bN; i++) {
    facts.at(i) = mMul(i, facts.at(i-1));
    invFacts.at(i) = mInv(facts.at(i));
  }
  sort(bS.begin(), bS.end());

  low.resize(bX+1);
  ll idx = 0;
  for (ll i = 0; i < bX+1; i++) {
    if (idx < (ll) bS.size() && bS.at(idx) == i)  idx++;
    low.at(i) = idx;
  }

  tbl.resize(bX+1, -1);
  ll ans = loose(bX, bS.size());
  cout << ans << endl;

  return 0;
}


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

string s, rs;
int n, k;
vector<vector<vector<int>>> dp;

int solve();

int main() {
  cin >> s >> k;
  n = s.size();
  rs = s;
  reverse(rs.begin(), rs.end());
  cout << solve() << endl;
  return 0;
}

int solve() {
  int res = 0;
  dp.assign(n + 1, vector(n + 1, vector<int>(k + 1, 0)));
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
      for (int l = 0; l <= k; ++l) {
        dp[i + 1][j + 1][l] = max(dp[i + 1][j][l], dp[i][j + 1][l]);
        if (s[i] == rs[j])
          dp[i + 1][j + 1][l] = max(dp[i + 1][j + 1][l], dp[i][j][l] + 1);
        else if (l != 0)
          dp[i + 1][j + 1][l] = max(dp[i + 1][j + 1][l], dp[i][j][l - 1] + 1);
        else
          dp[i + 1][j + 1][l] = max(dp[i + 1][j + 1][l], dp[i][j][l]);
      }
  for (int i = 0; i <= n; ++i)
    for (int j = 0; j <= n; ++j)
      for (int l = 1; l <= k; ++l)
        dp[i][j][l] = max(dp[i][j][l], dp[i][j][l - 1]);
  for (int i = 0; i <= n; ++i) {
    // even
    res = max(res, dp[i][n - i][k] * 2);
    // odd
    if (i > 0) res = max(res, dp[i - 1][n - i][k] * 2 + 1);
  }
  return res;
}

//Author:xht37
#include <bits/stdc++.h>

#define ui unsigned int
#define ll long long
#define ul unsigned ll
#define ld long double

#define pi pair <int, int>
#define fi first
#define se second
#define mp make_pair

#define ls (p << 1)
#define rs (ls | 1)
#define md ((t[p].l + t[p].r) >> 1)

#define vi vector <int>
#define pb push_back
#define pq priority_queue

#define dbg(x) cerr << #x" = " << (x) << endl
#define debug(...) fprintf(stderr, __VA_ARGS__)

#define fl(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)

using namespace std;

namespace io {
	const int SI = 1 << 21 | 1;
	char IB[SI], *IS, *IT, OB[SI], *OS = OB, *OT = OS + SI - 1, c, ch[100];
	int f, t;
	#define gc() (IS == IT ? (IT = (IS = IB) + fread(IB, 1, SI, stdin), IS == IT ? EOF : *IS++) : *IS++)
	inline void flush() {
		fwrite(OB, 1, OS - OB, stdout), OS = OB;
	}
	inline void pc(char x) {
		*OS++ = x;
		if (OS == OT) flush();
	}

	template <class I>
	inline void rd(I &x) {
		for (f = 1, c = gc(); c < '0' || c > '9'; c = gc()) if (c == '-') f = -1;
		for (x = 0; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + (c & 15), c = gc());
		x *= f;
	}
	template <class I>
	inline void rd(I &x, I &y) {
		rd(x), rd(y);
	}
	template <class I>
	inline void rd(I &x, I &y, I &z) {
		rd(x), rd(y), rd(z);
	}
	template <class I>
	inline void rda(I *a, int n) {
		for (int i = 1; i <= n; i++) rd(a[i]);
	}
	inline void rdc(char &c) {
		for (c = gc(); c < 33 || c > 126; c = gc());
	}
	inline void rds(char *s, int &n) {
		for (c = gc(); c < 33 || c > 126; c = gc());
		for (n = 0; c >= 33 && c <= 126; s[++n] = c, c = gc());
	}
	inline void rds(string &s) {
		for (c = gc(); c < 33 || c > 126; c = gc());
		for (s.clear(); c >= 33 && c <= 126; s.pb(c), c = gc());
	}

	template <class I>
	inline void print(I x, char k = '\n') {
		if (!x) pc('0');
		if (x < 0) pc('-'), x = -x;
		while (x) ch[++t] = x % 10 + '0', x /= 10;
		while (t) pc(ch[t--]);
		pc(k);
	}
	template <class I>
	inline void print(I x, I y) {
		print(x, ' '), print(y);
	}
	template <class I>
	inline void print(I x, I y, I z) {
		print(x, ' '), print(y, ' '), print(z);
	}
	template <class I>
	inline void printa(I *a, int n) {
		for (int i = 1; i <= n; i++) print(a[i], " \n"[i==n]);
	}
	inline void printc(char c) {
		pc(c);
	}
	inline void prints(char *s, int n) {
		for (int i = 1; i <= n; i++) pc(s[i]);
		pc('\n');
	}
	inline void prints(string s) {
		int n = s.length();
		while (t < n) pc(s[t++]);
		pc('\n'), t = 0;
	}
	struct Flush {
		~Flush() {
			flush();
		}
	} flusher;
}
using io::rd;
using io::rda;
using io::rdc;
using io::rds;
using io::print;
using io::printa;
using io::printc;
using io::prints;

const int N = 307, inf = 1e9;
int n, k, f[N][N][N];
char s[N];
bool v[N][N][N];

int F(int l, int r, int k) {
	if (k < 0) return -inf;
	if (r - l < 1) return r - l + 1;
	if (v[l][r][k]) return f[l][r][k];
	v[l][r][k] = 1;
	return f[l][r][k] = max(max(F(l + 1, r, k), F(l, r - 1, k)), F(l + 1, r - 1, k - (s[l] != s[r])) + 2);
}

int main() {
	rds(s, n), rd(k), print(F(1, n, k));
	return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define SZ(x) (int)(x).size()
#define int ll
#define F first
#define S second

const int N = 1e5 + 10;
vector<int> g[N];
int p[N], dp[N], ans, k;

void dfs(int v) {
	dp[v] = 1;
	for (auto u : g[v]) {
		dfs(u);
		dp[v] = max(dp[v], dp[u] + 1);
	}
	if (dp[v] == k - 1 && p[v] != 1) {
		dp[v] = 0;
		ans++;
	}
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
	int n;
	cin >> n >> k;
	k++;
	int x;
	cin >> x;
	if (x != 1) {
		ans++;
	}
	p[1] = 1;
	for (int i = 2; i <= n; i++) {
		int x;
		cin >> x;
		g[x].pb(i);
		p[i] = x;
	}
	dfs(1);
	cout << ans << '\n';
}

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

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

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

  sort(a,a+n);
  int64_t ans = 0,count = 1;
  for(int i = 0; i < n; i++){
    if(a[i] == a[i+1]){
      count++;
    }else{
      if( (count % 2) == 1){
        ans++;
      }
      count = 1;
    }
  }

  cout << ans << endl;
}


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

//#define int long long
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define rep(i,n) for(int i=0;i<n;++i)
#define rep1(i,n) for(int i=1;i<n;++i)
#define exrep(i, a, b) for(ll i = a; i < b; i++)
#define out(x) cout << x << endl
#define EPS (1e-7)
#define gearup ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<pair<int,int> > vpii;
typedef vector<vector<int> > vvi;
typedef vector<vector<char> > vvc;
typedef vector<vector<bool> > vvb;
typedef vector<vector<double> > vvd;
typedef vector<vector<string> > vvs;
typedef vector<ll> vl;
typedef vector<vector<ll> > vvl;
typedef vector<vector<vector<ll> > > vvvl;
ll MOD = 1000000007;
const long long L_INF = 1LL << 60;
const int INF = 2147483647; // 2^31-1
const double PI = acos(-1);
//cout<<fixed<<setprecision(10);

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;}
template<class T> void debug(T v){rep(i,v.size()) cout<<v[i]<<" ";cout<<endl;}
const ll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

struct BipartiteMatching {
  vector< vector< int > > graph;
  vector< int > match, alive, used;
  int timestamp;

  BipartiteMatching(int n) : graph(n), alive(n, 1), used(n, 0), match(n, -1), timestamp(0) {}

  void add_edge(int u, int v) {
    graph[u].push_back(v);
    graph[v].push_back(u);
  }

  bool dfs(int idx) {
    used[idx] = timestamp;
    for(auto &to : graph[idx]) {
      int to_match = match[to];
      if(alive[to] == 0) continue;
      if(to_match == -1 || (used[to_match] != timestamp && dfs(to_match))) {
        match[idx] = to;
        match[to] = idx;
        return true;
      }
    }
    return false;
  }

  int bipartite_matching() {
    int ret = 0;
    for(int i = 0; i < graph.size(); i++) {
      if(alive[i] == 0) continue;
      if(match[i] == -1) {
        ++timestamp;
        ret += dfs(i);
      }
    }
    return ret;
  }

  void output() {
    for(int i = 0; i < graph.size(); i++) {
      if(i < match[i]) {
        cout << i << "-" << match[i] << endl;
      }
    }
  }
};

signed main()
{
  gearup;
  int n; cin >> n;
  vpii r,b;
  rep(i,n){
    int x,y; cin >> x >> y;
    x--;y--;
    r.push_back({x,y});
  }
  rep(i,n){
    int x,y; cin >> x >> y;
    x--;y--;
    b.push_back({x,y});
  }
  //sort(all(r));
  //sort(all(b));

  BipartiteMatching bm(n + n);
  rep(i,n){
    rep(j,n){
      if(r[i].first < b[j].first && r[i].second < b[j].second) bm.add_edge(i,n+j);
    }
  }

  out(bm.bipartite_matching());
}

#include<bits/stdc++.h>

using namespace std;

#define LL long long
#define DD double
#define Pb push_back
#define Bp pop_back
#define Pf push_front
#define Fp pop_front
#define Ub upper_bound
#define Lb lower_bound
#define In insert
#define All(x) x.begin(), x.end()
#define mem(a, b) memset(a, b, sizeof(a))
#define fast ios_base::sync_with_stdio(0);cin.tie(0)
#define X first
#define Y second
#define mx1 10
#define mx2 110
#define mx3 1010
#define mx4 10010
#define mx5 100010
#define mx6 1000010

typedef vector<LL> Vl;
typedef vector<DD> Vd;
typedef vector<bool> Vb;
typedef vector<Vl> VVl;
typedef pair<LL, LL> Pll;
typedef pair<DD, DD> Pdd;
typedef vector<Pll> Vpl;
typedef vector<Pdd> Vpd;
typedef queue<LL> Ql;
typedef stack<LL> Sl;
typedef deque<LL> Dl;

LL _set(LL N, LL pos) {return N = N | (1 << pos);}
LL _reset(LL N, LL pos) {return N = N & ~(1 << pos);}
bool _check(LL N, LL pos) {return (bool)(N & (1 << pos));}
bool _upper(char a) {return a >= 'A' && a <= 'Z';}
bool _lower(char a) {return a >= 'a' && a <= 'z';}
bool _digit(char a) {return a >= '0' && a <= '9';}

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

///**************************DONE****************************///

typedef struct
{
    int x, y, col;
} pt;

bool cmp(pt A, pt B)
{
    if(A.x != B.x)
        return A.x < B.x;
}

pt P[2 * mx2];

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

    for(int i = 0; i < n; i++)
        cin >> P[i].x >> P[i].y, P[i].col = 1;
    for(int i = n; i < 2 * n; i++)
        cin >> P[i].x >> P[i].y, P[i].col = 2;

    sort(P, P + 2 * n, cmp);

    priority_queue<int> pq;
    int ans = 0;
    for(int i = 0; i < 2 * n; i++){
        if(P[i].col == 2){
            if(pq.size() == 0)
                continue;

            queue<int> q;
            while(!pq.empty()){
                int t = pq.top();
                pq.pop();

                if(t < P[i].y){
                    ans++;
                    break;
                }

                q.push(t);
            }

            while(!q.empty()){
                int t = q.front();
                pq.push(t);
                q.pop();
            }
        }
        else
            pq.push(P[i].y);
    }

    cout << ans << '\n';
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,(n)-1,0)
#define all(v) v.begin(), v.end()
#define endk '\n'
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
const ll mod2 = 998244353;
const ld eps = 1e-10;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n; ll m; cin >> n >> m;
  int v, p; cin >> v >> p;
  map<ll, int> mp;
  vector<ll> A(n);
  rep(i, n) {
    cin >> A[i];
    mp[A[i]]++;
  }
  sort(all(A));
  vector<ll> sum(n+1);
  rep(i, n) sum[i+1] = sum[i] + A[i];
  rrep(i, n) {
    ll margin = 0;
    ll t1 = upper_bound(all(A), A[i]) - begin(A);
    margin += t1 * m;
    ll t2 = upper_bound(all(A), A[i]+m) - begin(A);
    margin += (n-t2) * m;
    if(n-t2 >= p) {
      cout << n - i - 1 << endk;
      return 0;
    }
    ll rem = p - (n-t2);
    ll t3 = upper_bound(all(A), A[i]+m-1) - begin(A);
    margin += (rem-1) * m;
    if((t3-(rem-1)-t1) < 0) continue;
    margin += (A[i]+m) * (t3-(rem-1)-t1) - (sum[t3-(rem-1)]-sum[t1]);
    if(margin >= v * m) continue;
    else {
      cout << n - i - 1 << endk;
      return 0;
    }
  }
  cout << n << endk;
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
long long read()
{
	char ch=getchar();long long x=0,ff=1;
	while(ch<'0'||ch>'9') {if(ch=='-') ff=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*ff;
}
void write(long long aa)
{
	if(aa<0) putchar('-'),aa=-aa;
	if(aa>9) write(aa/10);
	putchar('0'+aa%10);
	return;
}
long long n,X,sum,ans;
long long b[100005],l[100005],r[100005],id[100005];
long long vis[100005];
long long F(long long aa)
{
	return (X-b[aa])*r[aa]+b[aa]*l[aa];
}
bool cmp(long long aa,long long bb)
{
	return F(aa)>F(bb);
}
int main()
{
	n=read(),X=read();
	for(long long i=1;i<=n;++i) b[i]=read(),l[i]=read(),r[i]=read(),id[i]=i,sum+=l[i]*b[i];
	if(sum==0) {puts("0");return 0;}
	sort(id+1,id+n+1,cmp);
	for(long long i=1;i<=n;++i)
	{
		if(sum>=F(id[i])) sum-=F(id[i]),ans+=X;
		else
		{
			sum-=F(id[i]);
			long long mx=X;
			for(long long j=1;j<=n;++j)
			{
				long long tmp=0;
				if(vis[j]) sum+=F(j);
				else sum+=F(id[i]);
				if(sum<=b[j]*l[j]) tmp=(sum-1)/l[j]+1;
				else sum-=b[j]*l[j],tmp=b[j]+(sum-1)/r[j]+1,sum+=b[j]*l[j];
				if(vis[j]) sum-=F(j);
				else sum-=F(id[i]);
				mx=min(tmp,mx);
			}
			ans+=mx;
			sum=0;
		}
		if(!sum) break;
		vis[id[i]]=1;
	}
	write(ans);
	return 0;
}


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

using Weight = long long;
using Vertex = int;
struct Edge {Vertex from, to; Weight weight;};
using Graph = std::vector<std::vector<Edge>>;

std::vector<std::vector<Vertex>> connected_component(const Graph& G) {
  std::vector<std::vector<Vertex>> cc;
  std::vector<bool> used(G.size());
  std::function<void(int)> dfs = [&](int v) {
    cc.back().push_back(v);
    used[v] = true;
    for(const auto& e: G[v]) if(!used[e.to]) dfs(e.to);
  };
  for(Vertex v = 0; v < G.size(); ++v) if(!used[v]) {
    cc.push_back(std::vector<Vertex>());
    dfs(v);
  }
  return cc;
}

using I = long long;

I com2(I n) {return n * (n - 1) / 2;}

bool check(const auto& G, auto s) {
  vector<int> color(G.size(), -1);
  function<bool(Vertex, int)> dfs = [&](auto v, auto c) {
    if(color[v] != -1) return color[v] == c;
    color[v] = c;
    c ^= 1;
    for(const auto& e: G[v]) if(!dfs(e.to, c)) return false;
    return true;
  };
  return dfs(s, 0);
}

int main() {
  I N, M;
  cin >> N >> M;
  Graph G(N);
  for(auto i=0; i<M; ++i) {
    int u, v;
    cin >> u >> v;
    --u; --v;
    G[u].push_back({u, v});
    G[v].push_back({v, u});
  }

  auto cc = connected_component(G);
  auto V = N - count_if(begin(cc), end(cc), [](const auto& v) {return v.size() == 1;});
  auto ans = N * N - V * V;
  I twocol = 0, obscure = 0;
  for(auto c: cc) if(c.size() != 1) {
    if(check(G, *begin(c))) ++twocol;
    else                    ++obscure;
  }
  ans += 2 * twocol + obscure;
  ans += 4 * com2(twocol) + 2 * com2(obscure);
  ans += 2 * twocol * obscure;
  cout << ans << endl;
}

#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
using ll = long long ;
using P = pair<int,int> ;
using pll = pair<long long,long long>;
constexpr int INF = 1e9;
constexpr long long LINF = 1e17;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979323846;
int v = 100005,e;
int c = 0;
vector<vector<int>> graph(v,vector<int>());
vector<bool> seen(v,false);
vector<int> ord(v);
vector<int> low(v);
vector<bool> isart(v,false);

void dfs(int i,int par=-1){
    seen[i] = true;
    ord[i] = low[i] = c++;
    int count = 0;

    for(int j:graph[i]){
        if(!seen[j]){
            dfs(j,i);
            ++ count;
            low[i] = min(low[i],low[j]);
            if(par != -1 && ord[i] <= low[j]) isart[i] = true;
        }else if(j!=par){
            low[i] = min(low[i],ord[j]);
        }
    }

    if(par==-1 && count>1) isart[i] = true;
    return;
}

int main(){
    cin >> v >> e;
    rep(i,e){
        int s,t;
        cin >> s >> t;
        graph[s].push_back(t);
        graph[t].push_back(s);
    }
    dfs(0);
    rep(i,v){
        if(isart[i]) cout << i << endl;
    }
    return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#define fo(i,a,b) for(ll i=a;i<=b;i++)
#define fd(i,a,b) for(ll i=a;i>=b;i--)
#define N 101000
#define ll long long
using namespace std;
ll sum,n,a[N],g1[N],g2[N];
ll gcd(ll x,ll y)
{
	if(x==-1||y==-1) return -x*y;
	return y==0?x:gcd(y,x%y);
}
ll dg(ll x)
{
	g1[1]=a[1];g2[n]=a[n];
	g1[0]=g2[n+1]=-1;
	fo(i,2,n) g1[i]=gcd(g1[i-1],a[i]);
	fd(i,n-1,1) g2[i]=gcd(g2[i+1],a[i]);
	ll gd=-1,k=0;
	fo(i,1,n)
	if(a[i]!=1)
	{
		gd=gcd(gcd(a[i]-1,g1[i-1]),g2[i+1]);
		k=i;
		if(((sum-1)/gd)%2==1) break;
		gd=-1;
	}
	if(gd!=-1)
	{
		fo(i,1,n) if(i!=k) a[i]=a[i]/gd;
		a[k]=(a[k]-1)/gd;
		sum=(sum-1)/(ll)gd;
		return 1-dg(x^1);
	}
	return 0;
}
int main()
{
	scanf("%lld",&n);
	fo(i,1,n) scanf("%lld",&a[i]),sum+=(ll)a[i];
	if(n%2==0)
	{
		if(sum%2==1) printf("First\n");
		else printf("Second\n");
		return 0;
	}
	if(sum%2==0) return printf("First\n"),0;
	if(dg(1)==1) printf("First\n");
	else printf("Second\n");
}

#include<bits/stdc++.h>
using namespace std;
#define N 305
double dp[N][N][N];
int n;
double fn(int x,int y,int z,int n) {
	if(x<0 || y<0 || z<0) {return 0;}
  	if(!x && !y && !z) {return 0;}
  	if(dp[x][y][z]>0) {return dp[x][y][z];}
  	int t=x+y+z;
  	return dp[x][y][z]=(n+x*fn(x-1,y,z,n)+y*fn(x+1,y-1,z,n)+z*fn(x,y+1,z-1,n))/t;
}
int main() {
  	int x=0,y=0,z=0,a;
  	cin>>n;
  	for(int i=0;i<n;i++) {
      cin>>a;
      x+=(a==1)?1:0;
      y+=(a==2)?1:0;
      z+=(a==3)?1:0;
    }
  	memset(dp,-1,sizeof(dp));
  	cout<<fixed<<setprecision(9);
  	double t=fn(x,y,z,n);
  	cout<<t<<endl;
return 0;
}


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

void solve(long long N, std::string S, long long Q, std::vector<long long> k)
{

    for (ll i = 0; i < Q; i++) {
        ll D = 0;
        ll M = 0;
        ll DM = 0;
        ll DMC = 0;
        ll ans = 0;
        for (ll j = 0; j < N; j++) {
            if (j - k[i] >= 0) {
                if (S[j - k[i]] == 'D') {
                    D--;
                    DM -= M;
                }
                if (S[j - k[i]] == 'M') {
                    M--;
                }
            }
            if (S[j] == 'D') {
                D++;
            }
            if (S[j] == 'M') {
                M++;
                DM += D;
            }
            if (S[j] == 'C') {
                DMC += DM;
            }
            ans = max(ans, DMC);
        }
        cout << ans << "\n";
    }
}

// Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
int main()
{
    long long N;
    scanf("%lld", &N);
    std::string S;
    std::cin >> S;
    long long Q;
    scanf("%lld", &Q);
    std::vector<long long> k(Q - 1 - 0 + 1);
    for (int i = 0; i < Q - 1 - 0 + 1; i++) {
        scanf("%lld", &k[i]);
    }
    solve(N, S, Q, std::move(k));
    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>;

ll sum[3][1000005];
ll combiDM[1000005];

int main() {
    int N;
    cin >> N;
    string S;
    cin >> S;
    int Q;
    cin >> Q;
    vector<int> k(Q);
    rep(i, Q) cin >> k[i];

    rep(j, 3) rep(k, N) sum[j][k] = 0;
    combiDM[0] = 0;

    string T = "DMC";
    rep(i, N) {
        rep(j, 3) {
            if (S[i] == T[j]) ++sum[j][i];
        }
    }

    rep(i, 2) {
        rep(j, N - 1) {
            if (i == 1) {
                combiDM[j + 1] = combiDM[j] + sum[0][j + 1] * sum[1][j + 1];
            }
            sum[i][j + 1] += sum[i][j];
        }
    }

    rep(i, Q) {
        vector<ll> ans(N);
        rep(j, N) {
            if (j < 2) continue;
            ans[j] += ans[j - 1];

            if (sum[2][j] != 1) continue;
            ans[j] += combiDM[j];
            if (j - k[i] < 0) continue;
            ans[j] -= (combiDM[j - k[i]] +
                       sum[0][j - k[i]] * (sum[1][j - 1] - sum[1][j - k[i]]));
        }

        cout << ans[N - 1] << endl;
    }
}


#include <iostream>
//#include <iomanip>
//#include <string>
#include <vector>
#include <algorithm>
//#include <utility>
//#include <set>
//#include <map>
//#include <queue>
//#include <deque>
//#include <bitset>
//#include <math.h>
using namespace std ;
using ll = long long ;
//using ld = long double ;
using vll = vector<ll> ;
//using vvll = vector<vll> ;
//using vc = vector<char> ;
//using vvc = vector<vc> ;
//using vb = vector<bool> ;
//using vvb = vector<vb> ;
//using pll = pair<ll,ll> ;
#define all(v) v.begin(),v.end()
//ll mod = 1000000007 ;
//long double pie = acos(-1) ;
//ll INF = 1000000000000 ;

//void yorn(bool a){if(a) cout << "Yes" << endl ; else cout << "No" << endl ;}
//void YorN(bool a){if(a) cout << "YES" << endl ; else cout << "NO" << endl ;}
//ll gcd(long long a,long long b){if(b==0) return a ; return gcd(b,a%b) ;}
//ll lcm(long long a,long long b){return a/gcd(a,b)*b ;}
//ll sa(long long a,long long b){if(a>b) return a-b ; return b-a ;}
//void fix_cout(){cout << fixed << setprecision(20) ;}

int main(){
	ll n,m,v,p ;
	cin >> n >> m >> v >> p ;
	vll a(n) ;
	for(auto &i:a) cin >> i ;
	sort(all(a)) ;
	reverse(all(a)) ;
	ll l,r,mid ;
	l = p-1 ;
	r = n ;
	while(l+1<r){
		mid = (l+r)/2 ;
		if(a.at(p-1)>a.at(mid)+m){
			r = mid ;
			continue ;
		}
		ll cnt = 0 ;
		cnt += m*(p-1+n-mid) ;
		for(int i=p-1;i<mid;i++) cnt += a.at(mid)+m-a.at(i) ;
		if(cnt>=m*v) l = mid ;
		else r = mid ;
	}
	cout << l+1 << endl ;
}

#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimization("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma GCC target ("avx2,avx,fma")
#define ll long long int
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define pb push_back
#define mp make_pair
#define rep(i,l,r) for(i=l;i<r;i++)
#define ld long double
#define ff first
#define ss second
#define pli pair<ll,int>
#define pi 3.1415926535897932384626433832
int main()
{
    io;
    int i,n;
    ll x;
    cin>>n>>x;
    vector<ll>b(n);
    vector<ll>l(n);
    vector<ll>u(n);
    vector<pli>p(n);
    vector<ll>pre(n);
    ll d=0;
    rep(i,0,n)
    {
    cin>>b[i]>>l[i]>>u[i];
    d-=l[i]*b[i];
    p[i]=mp(l[i]*b[i]+u[i]*(x-b[i]),i);
    }
    ll beg=0;
    ll r=n*x;
    //cout<<r;
    sort(p.begin(),p.end(),greater<pli>());
    pre[0]=p[0].ff;
    rep(i,1,n)
    pre[i]=pre[i-1]+p[i].ff;
    while(beg<=r)
    {
        //cout<<1;
        ll mid=(beg+r)/2;
        ll q=mid/x;
        ll rem=mid%x;
        ll ans;
        ll maxi=d;
        if(q==n)
            maxi=0;
        else
        rep(i,0,n)
        {
            ans=d;
            if(q!=0)
            {
            if(i<q)
                ans+=pre[q]-p[i].ff;
            else
                ans+=pre[q-1];
            }
            ans+=min(b[p[i].ss],rem)*l[p[i].ss]+max(rem-b[p[i].ss],0ll)*u[p[i].ss];
            maxi=max(ans,maxi);
        }
        if(maxi>=0)
        r=mid-1;
        else
        beg=mid+1;
    }
    cout<<beg;
    return 0;
}