#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < (n); i++)
#define REP1(i, n) for(int i = 1; i <= (n); i++)
#define REPD(i,a,b) for (int i=(a);i<(b);i++)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long ll;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef set<int> si;
typedef vector<si> vsi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef pair<int, int> pi;
typedef queue<int> qi;
typedef queue<pi> qpi;
typedef pair<ll, ll> pll;
typedef queue<pll> qpll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
const int mod = 1000000007;
const int INF = 1001001001;
// 小数点　<< fixed << setprecision(0) <<
// sort降順　sort(ALL(),greater<int>());
// 円周率　M_PI
// 文字判定　isupper islower
// 文字変換
// 順列　do {} while(next_permutation(ALL(X)));
// 最大値　LLONG_MAX
// a内でx以上　auto iter = lower_bound(ALL(a), x);
// a内でxより大きい　auto iter = upper_bound(ALL(a), x);
int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};
int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};
struct edge {
    int from; //出発点
    int to;   //到達点
    int cost; //移動コスト
};
typedef struct edge se;
typedef vector<edge> ve;
unsigned Euclidean_gcd(unsigned a, unsigned b) {
  if(a < b) return Euclidean_gcd(b, a);
  unsigned r;
  while ((r=a%b)) {
    a = b;
    b = r;
  }
  return b;
}

vpll PrimeFactorization(ll n) {
  vpll res;
  for (ll i=2; i*i<=n; i++) {
    if(n%i!=0) continue;
    ll ex=0;
    while(n%i==0) {
      ex++;
      n/=i;
    }
    res.push_back(pll(i,ex));
  }
  if(n!=1) res.push_back(pll(n,1));
  return res;
}

int main() {
  int n;
  cin >> n;
  char s[n];
  cin >> s;
  int mi=0;
  REP(i,n) {
    if(i>0&&s[i]=='E') {
      mi++;
    }
  }
  int temp=mi;
  REP(i,n-1) {
    if(s[i]=='W') temp++;
    if(s[i+1]=='E') temp--;
    mi=min(mi,temp);
  }
  cout << mi << endl;
  return 0;
}


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

#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define fr(i,k) for(i=0;i<k;i++)
#define deb(x) cerr<<#x<<"  = "<<x<<endl;
#define deb2(x,y) cerr<<#x<<" ="<<x<<endl<<#y<<" ="<<y<<endl;
#define SZ(x) (x).size();
#define ll long long
#define mod 1000000007
#define ff first
#define ss second
#define pb push_back
#define em emplace_back
#define ulli unsigned long long int
#define inf 1e18
#define endl "\n"
typedef vector<vector<ll>> vvll;
typedef vector<ll> vll;
typedef vector<pair<ll, ll>> vpll;
typedef pair<ll, ll> pll;
typedef vector<bool> vb;
void solve();

int main() {
	fastio;
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll t;
	t = 1;

	//cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}

ll dp[10001][101][2];

ll calc(string &k, ll pos, ll D, ll d, ll tight)
{
	if (dp[pos][d][tight] != -1)
		return dp[pos][d][tight];

	ll ub = tight ? (k[pos] - '0') : 9;

	if (pos == k.length() - 1)
	{
		ll ans = 0;
		for (ll x = 0; x <= ub; x++)
		{
			if (x % D == d)
				ans++;
		}

		return ans;
	}

	ll ans = 0;
	for (ll x = 0; x <= ub; x++)
	{
		ans = (ans + calc(k, pos + 1, D, (D + d - x % D) % D, tight && (x == ub))) % mod;
	}

	return dp[pos][d][tight] = ans;

}

inline void solve()
{
	ll D, i;
	string k;
	cin >> k >> D;

	memset(dp, -1, sizeof dp);

	cout << (mod + calc(k, 0, D, 0, 1) - 1) % mod << endl;
}

/*
    -ensure correct output format
    -ensure printing required output
    -reread the problem statement
  */

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll>pll;
typedef pair<ll,pair<ll,ll>>plll;
#define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
#define vll(v) v.begin(),v.end()
#define all(x) x.rbegin(),x.rend()
#define min3(a, b, c)   min(a, min(b, c))
#define max3(a, b, c)   max(a, max(b, c))
#define F first
#define S second
#define in  freopen("input.txt", "r", stdin)
#define out  freopen("output.txt", "w", stdout)
#define minheap int,vector<int>,greater<int>
#define pb push_back
#define eb emplace_back
#define ischar(x)  (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z'))
#define isvowel(ch) ((ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')||(ch=='A'|| ch=='E' || ch=='I'|| ch=='O'|| ch=='U'))
#define bug cout<<"BUG"<<endl;
const int Max = 2e6 + 10;
const int Mod = 1e9 + 7;
const double PI  =3.141592653589793238463;
bool compare(const pair<ll,ll> &a, const pair<ll,ll> &b)
{
       return (a.first > b.first);
}
ll lcm(ll a,ll b)
{
    if(a==0 || b==0)return 0;

    return a/__gcd(a,b)*b;
}

void input(ll ara[],ll n)
{
    for(ll i=0; i<n; i++)cin>>ara[i];
}
void print(ll ara[],ll n)
{
    for(ll i=0; i<n; i++)
        cout<<ara[i]<<" ";
    cout<<endl;
}

int main()
{

   fastread();

   ll i,j,n,m,p,a,sum=0,k,t,b,c,d,cnt=0,q,l,r,ans=0;

      bool flag=false;

      string str,ptr;

   cin>>a>>b;

   if(b==1)
   {
       cout<<0<<endl;

       return 0;
   }

   a--;
   b--;

    n=b/a;

    if(b%a)n++;

    cout<<n<<endl;

}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> P;
typedef pair<ll,ll> l_l;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;
#define pb push_back
#define sz(x) (int)(x).size()
#define fi first
#define se second
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
const int INF=1001001000;
const int mINF=-1001001000;
const ll LINF=1010010010010010000;
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;
}
//グリッド：（典型）dp,dfs,bfs,最短経路,その他
string s[8];
int ng[8][8];
bool flg;
void dfs(int r){
    if(r==8){
        flg=1;
        return;
    }
    for(int c=0;c<8;c++){
        if(s[r][c]=='Q'){
            dfs(r+1);
            return;
        }
    }
    for(int c=0;c<8;c++){
        if(ng[r][c])continue;
        s[r][c]='Q';
        for(int j=0;j<8;j++){
            if(r+j<8)ng[r+j][c]++;
            if(r-j>=0)ng[r-j][c]++;
            if(c+j<8)ng[r][c+j]++;
            if(c-j>=0)ng[r][c-j]++;
            if(r+j<8&&c+j<8)ng[r+j][c+j]++;
            if(r+j<8&&c-j>=0)ng[r+j][c-j]++;
            if(r-j>=0&&c+j<8)ng[r-j][c+j]++;
            if(r-j>=0&&c-j>=0)ng[r-j][c-j]++;
        }
        dfs(r+1);
        if(flg)return;
        s[r][c]='.';
        for(int j=0;j<8;j++){
            if(r+j<8)ng[r+j][c]--;
            if(r-j>=0)ng[r-j][c]--;
            if(c+j<8)ng[r][c+j]--;
            if(c-j>=0)ng[r][c-j]--;
            if(r+j<8&&c+j<8)ng[r+j][c+j]--;
            if(r+j<8&&c-j>=0)ng[r+j][c-j]--;
            if(r-j>=0&&c+j<8)ng[r-j][c+j]--;
            if(r-j>=0&&c-j>=0)ng[r-j][c-j]--;
        }
    }
}
int main(){
    rep(i,8)s[i]=string(8,'.');
    int n;cin>>n;
    memset(ng,0,sizeof(ng));
    for(int i=0;i<n;i++){
        int r,c;cin>>r>>c;
        s[r][c]='Q';
        for(int j=0;j<8;j++){
            if(r+j<8)ng[r+j][c]++;
            if(r-j>=0)ng[r-j][c]++;
            if(c+j<8)ng[r][c+j]++;
            if(c-j>=0)ng[r][c-j]++;
            if(r+j<8&&c+j<8)ng[r+j][c+j]++;
            if(r+j<8&&c-j>=0)ng[r+j][c-j]++;
            if(r-j>=0&&c+j<8)ng[r-j][c+j]++;
            if(r-j>=0&&c-j>=0)ng[r-j][c-j]++;
        }
    }
    flg=0;
    dfs(0);
    rep(i,8)cout<<s[i]<<endl;
    return 0;
}

#include <algorithm>
#include <cmath>
#include <cstdio>

#define int long long
#define dotimes(i, n) for (int i : range(n))

using namespace std;

class range {
  class iterator {
    int i, s;
  public:
    iterator(int i, int s): i(i), s(s) {}
    int& operator*() {
      return i;
    }
    void operator++() {
      i += s;
    }
    bool operator!=(iterator const& that) {
      return i < that.i;
    }
  };
  iterator b, e;
public:
  range(int e): b({0, 1}), e({e, 1}) {}
  range(int b, int e): b({b, 1}), e({e, 1}) {}
  range(int b, int e, int s): b({b, s}), e({e, s}) {}
  iterator begin() {
    return b;
  }
  iterator end() {
    return e;
  }
};

int rint() {
  int n;
  scanf("%lld", &n);
  return n;
}

void wint(int n) {
  printf("%lld\n", n);
}

template<typename T>
inline int size(T container) {
  return static_cast<int>(container.size());
}

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

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

signed main() {
  const int k = rint();
  int rf[8] = {}, p[8 - k];
  bool cf[8] = {};
  dotimes(i, k) {
    int r = rint();
    int c = rint();
    rf[r] = c + 1;
    cf[c] = true;
  }
  for (int i = 0, j = 0, c = 0; i < 8; i++)
    if (!rf[i]) {
      while (cf[c])
        c++;
      p[j++] = ++c;
    }
  int a[8];
  for (;; next_permutation(p, p + 8 - k)) {
    for (int i = 0, j = 0; i < 8; i++)
      a[i] = rf[i] ? rf[i] : p[j++];
    dotimes(i, 8)
      dotimes(j, i)
        if (abs(a[j] - a[i]) == abs(j - i))
          goto failed;
    break;
  failed:
    ;
  }
  dotimes(i, 8) {
    dotimes(j, 8)
      putchar(a[i] == j + 1 ? 'Q' : '.');
    putchar('\n');
  }
  return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <utility>
#include <numeric>

using namespace std;

const int INF = 2E9;
const uint64_t MOD = 1E9 + 7;

int partition(vector<int> &a)
{
	int x = a.back();
	int id = -1;

	for (int i = 0; i < a.size() - 1; i++)
	{
		if (a.at(i) <= x)
		{
			id++;
			swap(a.at(i), a.at(id));
		}
	}
	swap(a.at(id + 1), a.back());

	return id + 1;
}

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

	vector<int> a(n);
	for (int i = 0; i < n; i++)
	{
		cin >> a.at(i);
	}

	int p = partition(a);

	for (int i = 0; i < n; i++)
	{
		cout << (i == 0 ? "" : " ");
		if (i == p)
		{
			cout << "[" << a.at(i) << "]";
		}
		else
		{
			cout << a.at(i);
		}
	}

	cout << endl;
}

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

struct StQuery
{
  StQuery() : m_nLeft(0), m_nRigt(0) { }

  int m_nLeft;
  int m_nRigt;
};

void input(string& rsStr, vector<StQuery>& rvoQuery)
{
  int nStrSiz, nQuerySiz;
  cin >> nStrSiz >> nQuerySiz;
  rvoQuery.resize(nQuerySiz);

  cin >> rsStr;

  for (StQuery& roQuery : rvoQuery)
    cin >> roQuery.m_nLeft >> roQuery.m_nRigt;
}

void calcSubStrACCnt(string sStr, const vector<StQuery>& cnrvoQuery)
{
  vector<int> vnCumlSum(sStr.size() + 1);      // 累積和

  //vnCumlSum_ix 0 1 2 3 4 5 6 7 8
  //sStr_pos      1 2 3 4 5 6 7 8
  //sStr          A C A C T A C G
  //sStr_ix       0 1 2 3 4 5 6 7
  for (int nBgn = 0; nBgn < vnCumlSum.size() - 1; nBgn++)
  {
    vnCumlSum[ nBgn + 2 ] = vnCumlSum[ nBgn + 1 ];
    if (sStr[nBgn] == 'A' && sStr[nBgn + 1] == 'C')
      vnCumlSum[ nBgn + 2 ]++;
  }

 for (int i = 0; i < cnrvoQuery.size(); i++)
  {
    cout << vnCumlSum[ cnrvoQuery[i].m_nRigt ] - vnCumlSum[ cnrvoQuery[i].m_nLeft ];
    cout << endl;
  }
}

int main()
{
  string sStr;
  vector<StQuery> voQuery;

  input(sStr, voQuery);
  calcSubStrACCnt(sStr, voQuery);

  return 0;
}


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

int main(){
	map<char, int> m;
	m['I'] = 1;m['V'] = 5;m['X'] = 10;m['L'] = 50;
	m['C'] = 100;m['D'] = 500;m['M'] = 1000;
	string s;
	while(cin >> s){
		int i = 0, ans = 0;
		while(i < s.size()){
			char c = s[i];
			int t = 0;
			for(i;c == s[i] && i < s.size()-1;i++)t += m[c];
			if(m[c] < m[s[i]])ans -= t;
			else ans += t;
			if(i == s.size()-1)ans += m[s[i++]];
		}
		cout << ans << endl;
	}
	return 0;
}

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

int main() {
    int N;
    cin >> N;
    map<ll, ll> A;
    rep(i, N) {
        ll tmp;
        cin >> tmp;
        A[tmp]++;
    }

    vl st;
    for (auto x : A) {
        int y = x.second;
        while (y >= 2) {
            y -= 2;
            st.push_back(x.first);
        }
    }

    if (st.size() < 2) {
        cout << 0 << endl;
    } else {
        sort(st.begin(), st.end());
        reverse(st.begin(), st.end());

        ll ans = st[0] * st[1];

        cout << ans << endl;
    }
}


#include<iostream>
using namespace std;
int cnt = 0;
int n;
int a[1000000];
int w[500000];
int G[500000];
int m;
int shellsort();
int aho(int g);

int shellsort()
{
	m = n / 2;
	if (m == 0)
	{
		m = 1;
	}
	//cout << m << endl;
	for (int i = 0; i < m; i++)
	{
		if (i == 0)
		{
			G[0] = m;
		}
		else
			G[i] = G[i - 1] / 2;
		if (G[i] == 0)
		{
			m = i;
			break;
		}
		//cout << G[i];
		//if (i != m - 1)cout << " ";
	}
	cout << m << endl;
	for (int i = 0; i < m; i++)
	{
		cout << G[i];
		if (i != m - 1)
		{
			cout << " ";
		}
	}
	cout << endl;
	for (int i = 0; i < m; i++)
	{
		aho(G[i]);
	}
	return 0;
}
int aho(int g)
{
	for (int i = g; i < n; i++)
	{
		int v = a[i];
		int j = i - g;
		while (j>=0 && a[j] > v)
		{
			a[j + g] = a[j];
			j = j - g;
			cnt++;
		}
		a[j + g] = v;
	}
	return 0;
}
int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	shellsort();
	cout << cnt << endl;
	for (int i = 0; i < n; i++)
	{
	 cout << a[i] << endl;
	}

}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <string>
#include <vector>
#include <limits.h>
#include <stack>
#include <queue>
#define maxn 1e9
#define pi acos(-1)
#define LL long long
using namespace std;
double aabs(double x)
{
	if(x<0)return -x;
	return x;
}
int gcd(int a,int b)
{
	if(a%b==0)return b;
	return gcd(b,a%b);
}
struct card{char suit,value;};
void bubble(struct card A[],int N)///冒泡排序；
{
	for(int i=0;i<N;i++)
		for(int j=N-1;j>=i+1;j--)
			if(A[j].value<A[j-1].value)
			{
				card t=A[j];
				A[j]=A[j-1];
				A[j-1]=t;
			}
}
void selection(struct card A[],int N)///选择排序；
{
	for(int i=0;i<N;i++)
	{
		int minj=i;
		for(int j=i;j<N;j++)
		{
			if(A[j].value<A[minj].value)minj=j;
		}
		card t=A[i];
		A[i]=A[minj];
		A[minj]=t;
	}
}
LL cnt;
int l;
int a[1000000];
int n;
vector<int>G;
void insertionSort(int A[],int n,int g)///指定了间隔g的插入排序
{
	for(int i=g;i<n;i++)
	{
		int v=A[i];
		int j=i-g;
		while (j>=0&&A[j]>v) {
			A[j+g]=A[j];
			j-=g;
			cnt++;
		}
		A[j+g]=v;
	}
}
void shellSort(int A[],int n)///希尔排序；
{
	for(int h=1;;)//生成数列G={1,4,13,40,121,364,1093,.....}
	{
		if(h>n)break;
		G.push_back(h);
		h=3*h+1;
	}
	for(int i=G.size()-1;i>=0;i--)///按逆序指定G[i]=g;
	{
		insertionSort(A, n, G[i]);
	}
}
bool isStable(struct card c1[],struct card c2[],int N)///判断稳定；
{
	for(int i=0;i<N;i++)
	{
		if(c1[i].suit!=c2[i].suit)return false;
	}
	return true;
}
int main()
{
	card c1[107],c2[107];
	int n;
	char ch;
	cin>>n;
	for(int i=0;i<n;i++)scanf("%d",&a[i]);
	cnt=0;
	shellSort(a, n);
	cout<<G.size()<<endl;
	for(int i=G.size()-1;i>=0;i--)
	{
		printf("%d",G[i]);
		if(i)printf(" ");
	}
	printf("\n");
	printf("%lld\n",cnt);
	for(int i=0;i<n;i++)printf("%d\n",a[i]);
	return 0;
}


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

  ll p[m];
  string s[m];
  rep(i,m) cin >> p[i] >> s[i];

  ll acnum[n+1];
  for(ll i = 0; i < m; i++){
    if(s[i] == "AC"){
      acnum[p[i]] = 1;
    }
  }

  ll ac = 0, wa = 0;
  ll ok[n+1];
  for(ll i = 1; i <= n; i++) ok[i] = 0;
  for(ll i = 0; i < m; i++){
    if(s[i] == "WA" && ok[p[i]] == 0 && acnum[p[i]] == 1){
      wa++;
    }
    if(s[i] == "AC" && ok[p[i]] == 0){
      ok[p[i]] = 1;
      ac++;
    }
  }

  cout << ac << " " << wa << endl;
}

#include <algorithm>
#include <cassert>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

#define int long long int
#define rep(i, n) for (int i = 0; i < n; ++i)
#define all(x) (x).begin(), (x).end()
#define capi(x) int x;cin>>x
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

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

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

    int fl[100001];
    memset(fl, 0, sizeof(int) * 100001);

    int pe = 0;
    int ac = 0;

    rep(i, m) {
        int p; string s;
        cin >> p >> s;

        if (s == "AC") {
            if (fl[p] >= 0) {
                ++ac;
                pe += fl[p];
                fl[p] = -1;
            }
        } else {
            if (fl[p] >= 0) ++fl[p];
        }
    }

    cout << ac << " " << pe;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(void){
    string S;
    int counter=0;
    cin>>S;

    for(int i=0;i<3;i++){
        if(S[i]=='R'){
            counter++;
            for(int j=1;j<3;j++){
                if(S[i+j]=='R'){
                    counter++;
                    if(j==2){
                        cout<<counter<<endl;
                        return 0;
                    }
                }else{
                    cout<<counter<<endl;
                    return 0;
                }
            }
        }
    }

    cout<<counter<<endl;

    return 0;
}

#include <bits/stdc++.h>

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

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

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

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

int main() {
  ll D; cin >> D;
  ll result = 0;
  rep(dig,19) {
    rep(pm,1<<((dig+1)/2-1)) {
      ll td = D, l = pow(10,dig-1), r = 1;
      bool plus[(dig+1)/2]; rep(i,(dig+1)/2) plus[i] = pm&(1<<i); plus[(dig+1)/2-1] = true;
      ll diff[(dig+1)/2];
      per(i,(dig+1)/2) {
        ll left = (td/r%10+10)%10;
        if (plus[i]) { diff[i] = (10-left)%10; td -= (l-r)*diff[i]; }
        else { diff[i] = left; td += (l-r)*diff[i]; }
        l /= 10; r *= 10;
      }
      bool ok = td==0;
      rep(i,(dig+1)/2-1) { if (diff[i]==0&&plus[i]) ok = false; }
      if (!ok) continue;
      // cout << dig << "," << pm << "->" << td << "..."; debug(diff,diff+(dig+1)/2);
      ll tmpr = 1; rep(i,(dig+1)/2) {
        if (i==0&&dig%2==1) tmpr *= 10;
        else if (i==(dig+1)/2-1) tmpr *= 9-diff[i];
        else tmpr *= 10-diff[i];
      }
      result += tmpr;
    }
  }
  cout << result << endl;
  return 0;
}


// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <stdio.h>
#include <string.h>

int main()
{
int n;
int runner;
int score;
int out;
char nyuuryoku[114514];
    scanf("%d",&n);
        for(int i=0;i<n;i++){
            runner=0;
            score=0;
            out=0;
            while(out<3){
                scanf("%s",nyuuryoku);
                    if(strcmp(nyuuryoku,"HIT")==0){
                        runner=runner+1;
                    }
                    else if(strcmp(nyuuryoku,"HOMERUN")==0){
                        score=score+runner+1;
                        runner=0;
                    }
                    else if(strcmp(nyuuryoku,"OUT")==0){
                        if(out==2&&runner>3){
                            score=score+runner-3;
                        }

                           out=out+1;
                    }
            }
            printf("%d\n",score);
        }

}
// GCC reference:
//   https://gcc.gnu.org/

// C++ language references:
//   https://msdn.microsoft.com/library/3bstk3k5.aspx
//   http://www.cplusplus.com/
//   https://isocpp.org/
//   http://www.open-std.org/jtc1/sc22/wg21/

// Boost libraries references:
//   http://www.boost.org/doc/

#include <bits/stdc++.h>
//#include <boost/multiprecision/cpp_int.hpp>
//namespace mp = boost::multiprecision;

using namespace std;

const double PI = 3.14159265358979323846;
typedef long long ll;
const double EPS = 1e-9;
#define rep(i, n) for (int i = 0; i < (n); ++i)
typedef pair<ll, ll> P;
const ll INF = 10e17;
#define cmin(x, y) x = min(x, y)
#define cmax(x, y) x = max(x, y)
#define ret() return 0;

double equal(double a, double b) {
    return fabs(a - b) < DBL_EPSILON;
}

std::istream &operator>>(std::istream &in, set<int> &o) {
    int a;
    in >> a;
    o.insert(a);
    return in;
}

std::istream &operator>>(std::istream &in, queue<int> &o) {
    ll a;
    in >> a;
    o.push(a);
    return in;
}

bool contain(set<int> &s, int a) { return s.find(a) != s.end(); }

typedef priority_queue<ll, vector<ll>, greater<ll> > PQ_ASK;

class Match {

    multiset<ll> l, r;

public:
    void add(P p) {
        this->l.insert(p.first);
        this->r.insert(p.second);
    }

    ll point() {
        auto itl = l.end();
        itl--;
        ll lr = *itl;
        auto itr = r.begin();
        ll rl = *itr;

        return max<ll>(rl - lr + 1, 0);
    }

    void pop(P p) {
        l.erase(l.find(p.first));
        r.erase(r.find(p.second));
    }

};

int main() {
    int n;
    cin >> n;
    vector<P> v(n);
    for (P &p:v)cin >> p.first >> p.second;

    ll ans_one = [&] {
        Match a, b;
        rep(i, n) {
            b.add(v[i]);
        }

        ll ans = 0;
        rep(i, n) {
            b.pop(v[i]);
            a.add(v[i]);

            ll now = b.point() + a.point();
            cmax(ans, now);

            a.pop(v[i]);
            b.add(v[i]);
        }
        return ans;
    }();

    ll ans_split = [&]() -> ll {

        sort(v.begin(), v.end(), [](P p1, P p2) {
            return p1.second < p2.second;
        });

        Match a, b;
        for (P p : v) b.add(p);
        ll ans = 0;
        rep(i, n - 1) {
            P p = v[i];
            a.add(p);
            b.pop(p);
            ll now = a.point() + b.point();
            cmax(ans, now);
        }
        return ans;
    }();

    ll ans = max(ans_split, ans_one);

    cout << ans << endl;

}


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

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    vector<int> AB(2);
    for (int i=0;i<2;++i) cin >> AB[i];
    int K; cin >> K;
    for (int i=0;i<K;++i){
        if (AB[i&1]&1) --AB[i&1];
        AB[(i&1)^1]+=AB[i&1]/2;
        AB[i&1]/=2;
    }
    cout << AB[0] << ' ' << AB[1] << '\n';
}

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

int main() {
  ll a, b, k;
  cin >> a >> b >> k;
  rep(i, k) {
    if (i%2) {
      if (b%2) {
        b--;
        a += b/2;
        b /= 2;
      } else {
        a += b/2;
        b /= 2;
      }
    } else {
      if (a%2) {
        a--;
        b += a/2;
        a /= 2;
      } else {
        b += a/2;
        a /= 2;
      }
    }
  }
  cout << a << ' ' << b << endl;
}


#include <bits/stdc++.h>
#define REP(i, e) for(int (i) = 0; (i) < (e); ++(i))
#define FOR(i, b, e) for(int (i) = (b); (i) < (e); ++(i))
#define ALL(c) (c).begin(), (c).end()
#define PRINT(x) cout << (x) << "\n"
using namespace std;
using ll = long long; using pint = pair<int, int>; using pll = pair<ll, ll>;
const long long MOD = 1000000007;

ll N, K, D[10];

bool check(ll x){
    while(x > 0){
        ll d = x % 10;
        REP(i, K){
            if(d == D[i]) return false;
        }
        x /= 10;
    }
    return true;
}

signed main(){
    cin >> N >> K;
    REP(i, K) cin >> D[i];
    ll ans = N;
    while(true){
        if(check(ans)) break;
        ans++;
    }
    PRINT(ans);
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const long long INF = 1LL << 60;

int main(){
    int N, K;
    cin >> N >> K;
    vector<int> D(10, 0);
    for(int i=0; i<K; i++) {
        int a;
        cin >> a;
        D[a] = 1;
    }

    for(int i=N; i<=100000; i++) {
        int num = i;
        bool flg = true;
        while(num) {
            int x = num % 10;
            if (D[x] == 1) {
                flg = false;
                break;
            }
            num /= 10;
        }
        if(flg && i>= N) {
            cout << i << endl;
            return 0;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
#define lor(a,b,c) for(register int a=b;a<=c;++a)
#define ror(a,b,c) for(register int a=c;a>=b;--a)
typedef long long ll;

const int N=3e5+5;
const ll MOD=1e9+7;

char s[N]; int n;
ll f[N][3][3],ans;

inline void inc(ll &a,ll b){
	(a+=b)>=MOD?a-=MOD:a;
}

inline void trans(int &a,int &b,int c){
	if(!c){
		++b; if(b>=3) b-=2;
	}
	else{
		if(b) --b;
		else ++a,a=min(a,2);
	}
}

int main(){

	scanf("%s",s+1); n=strlen(s+1);
	f[0][0][0]=1ll;
	lor(k,1,n){
		if(s[k]!='0'){
			lor(i,0,2) lor(j,0,2){
				int a=i,b=j; trans(a,b,1);
				inc(f[k][a][b],f[k-1][i][j]);
			}
		}
		if(s[k]!='1'){
			lor(i,0,2) lor(j,0,2){
				int a=i,b=j; trans(a,b,0);
				inc(f[k][a][b],f[k-1][i][j]);
			}
		}
	}
	lor(i,0,2) lor(j,0,i) inc(ans,f[n][i][j]);
	printf("%lld\n",ans);

	return 0;
}


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

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

  // person q is stopped by construction i
  // S_i <= D_q + X_i < T_i
  // S_i - X_i <= D_q < T_i - X_i
  // for i of smallest X_i

  vector<pair<int, pair<int, int>>> X_interval(N);
  for(int i = 0; i < N; i++){
    int s, t, x;
    cin >> s >> t >> x;
    X_interval[i] = make_pair(x, make_pair(s - x, t - x));
  }

  vector<int> D(Q);
  for(auto& x: D){
    cin >> x;
  }

  vector<pair<int, pair<int, bool>>> time_x_add;
  for(int i = 0; i < N; i++){
    int x = X_interval[i].first;
    int begin_time = X_interval[i].second.first, end_time = X_interval[i].second.second;
    time_x_add.push_back(make_pair(begin_time, make_pair(x, true)));
    time_x_add.push_back(make_pair(end_time, make_pair(x, false)));
  }
  sort(time_x_add.begin(), time_x_add.end());

  int next_event_idx = 0;
  set<int> X;
  for(int q = 0; q < Q; q++){
    while(next_event_idx < 2 * N && time_x_add[next_event_idx].first <= D[q]){
      int x = time_x_add[next_event_idx].second.first;
      bool add = time_x_add[next_event_idx].second.second;
      if(add){
        X.insert(x);
      }else{
        X.erase(x);
      }
      next_event_idx++;
    }
    if(X.size() > 0){
      cout << *X.begin() << endl;
    }else{
      cout << -1 << endl;
    }
  }

}

#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cctype>
#define rep(i,x,y) for(int i=x; i<=y; ++i)

using namespace std;
const int N=17,M=40000,INF=1000000000;
int n,m,f[M],q[M],tot,dis[N][N],u,v,c,g[N][M];

int getint()
{
	char ch;
	int f=1;
	while(!isdigit(ch=getchar())) if(ch=='-') f=-1;
	int x=ch-48;
	while(isdigit(ch=getchar())) x=x*10+ch-48;
	return x*f;
}

int query1(int x)
{
	int rt=0;
	rep(i,1,n)
		if(x&(1<<i-1))
			rep(j,i+1,n)
				if(x&(1<<j-1) && dis[i][j]!=INF)
					rt+=dis[i][j];
	return rt;
}

int query2(int x,int y)
{
	int rt=0,maxn=0;
	rep(i,1,n)
		if(x&(1<<i-1))
			maxn=max(maxn,g[i][y]);
	return maxn;
}

int main()
{
	n=getint(),m=getint();
	rep(i,1,n) rep(j,1,n) dis[i][j]=i==j?0:INF;
	rep(i,1,m) u=getint(),v=getint(),dis[u][v]=dis[v][u]=c=getint(),tot+=c;
 	rep(i,1,n)
		rep(j,0,(1<<n)-1)
			rep(k,1,n)
				if(dis[i][k]!=INF && j&(1<<k-1))
					g[i][j]+=dis[i][k];
	rep(i,1,(1<<n)-1) f[i]=-INF;
	f[1]=0;
	rep(i,1,(1<<n)-2)
		if(f[i]!=-INF)
		{
			rep(j,1,n)
				if(!(i&(1<<j-1)))
				{
					int maxn=0;
					rep(k,1,n)
						if(i&(1<<k-1) && dis[j][k]!=INF)
							maxn=max(maxn,dis[j][k]);
					if(maxn) f[i|(1<<j-1)]=max(f[i|(1<<j-1)],f[i]+maxn);
				}
		}

	rep(i,1,(1<<n)-1)
	{
		if(!(i&1) || !(i&(1<<n-1))) f[i]=-INF;
		q[i]=query1(i);
	}

	rep(i,1,(1<<n)-1)
		if(f[i]!=-INF)
			for(int j=((1<<n)-1)^i; j; j=(j-1)&(((1<<n)-1)^i))
				f[i|j]=max(f[i|j],f[i]+q[j]+query2(i,j));

	printf("%d\n",tot-f[(1<<n)-1]);
	return 0;
}


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

const int mod=1000000007;
int n,m;
int ca,cb;
ll a[1001],b[1001];
set<ll> sa,sb;
int main(){
    cin>>n>>m;
    bool flag=false;
    rep(i,n){
        cin>>a[i];
        if(sa.count(a[i])==0) sa.insert(a[i]);
        else flag=true;
    }
    rep(i,m){
        cin>>b[i];
        if(sb.count(b[i])==0) sb.insert(b[i]);
        else flag=true;
    }
    if(flag){
        cout<<0<<endl;
        return 0;
    }
    ll ans=1;
    for(int i=n*m;i>=1;--i){
        int ac=sa.count(i),bc=sb.count(i);
        if(ac==0&&bc==0){
            ans*=(1ll*ca*cb-n*m+i);
        }
        else if(ac==0){
            ++cb;
            ans*=1ll*ca;
        }
        else if(bc==0){
            ++ca;
            ans*=1ll*cb;
        }
        else ++ca,++cb;
        ans%=mod;
    }
    cout<<ans<<endl;
    return 0;
}

#include <cassert>
#include "limits.h"
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <complex>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
#include <random>
#include <memory>
#include <utility>

#define rep(i, a, b) for (long long (i) = (a); i < (b); i++)
#define all(i) i.begin(), i.end()
#define debug(i) std::cerr << "debug " <<"LINE:"<<__LINE__<<"  "<< #i <<":"<< i << std::endl

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, std::pair<T1, T2> pa) {
  return os << pa.first << " " << pa.second;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> vec) {
  for (int i = 0; i < vec.size(); i++)os << vec[i] << (i + 1 == vec.size() ? "" : " ");
  return os;
}

template<typename T1,typename T2>
inline bool chmax(T1& a,T2 b){return a<b && (a=b,true);}

template<typename T1,typename T2>
inline bool chmin(T1& a,T2 b){return a>b && (a=b,true);}

long long pow_mod(long long a, long long b, long long mod=-1) {
  if ((a == 0)||(mod!=-1&&a%mod==0)) {
    return 0;
  }

  long long x = 1;

  while (b > 0) {
    if (b & 1) {
      x = (mod!=-1)?(x * a) % mod:x*a;
    }
    a = (mod!=-1)?(a * a) % mod:a*a;
    b >>= 1;
  }
  return x;
}

// const long long MOD = 998244353;
const long long MOD = 1e9 + 7;

using ll = long long;
using P = std::pair<long double, long double>;

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

  ll n,m;
  std::cin>>n>>m;

  std::vector<ll> a(n*m+1,0),b(n*m+1,0);

  rep(i,0,n){
    ll temp;
    std::cin>>temp;
    a[temp]++;
  }
  rep(i,0,m){
    ll temp;
    std::cin>>temp;
    b[temp]++;
  }

  rep(i,1,n*m+1){
    if(a[i]>1||b[i]>1){
      std::cout<<0<<"\n";
      return 0;
    }
    a[i]+=a[i-1];
    b[i]+=b[i-1];
  }

  ll ans=1;

  for(ll i=n*m;i>0;i--){
    bool isa=(a[i]!=a[i-1]);
    bool isb=(b[i]!=b[i-1]);
    if(isa){
      if(!isb){
        ans=(ans*(m-b[i]))%MOD;
      }
    }else{
      if(isb){
        ans=(ans*(n-a[i]))%MOD;
      }else{
        ll num=(n-a[i])*(m-b[i]);
        if(num<=n*m-i){
          ans=0;
        }
        ans=(ans*(num+i-n*m))%MOD;
      }
    }
  }

  std::cout<<ans<<"\n";

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int N;
const int MAXV = 1000005;
int A[1005][1005];
int ID[1005][1005];
vector<int> to[MAXV];

int toId(int i, int j)
{
  if (i > j)
  {
    swap(i, j);
  }
  return ID[i][j];
}

vector<int> dp(MAXV, -1);
vector<bool> visited(MAXV, 0);
int dfs(int u)
{
  if (visited[u])
  {
    return dp[u]; // 訪問済だが、dpが未決定の場合は閉路が存在
  }
  visited[u] = 1;
  int ret = 1;
  for (auto v : to[u])
  {
    int res = dfs(v);
    if (res == -1)
      return -1;
    ret = max(ret, res + 1);
  }
  return dp[u] = ret;
}

int main()
{
  cin >> N;
  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < N - 1; j++)
    {
      cin >> A[i][j];
      A[i][j]--;
    }
  }
  int V = 0;
  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < N; j++)
    {
      if (i < j)
      {
        ID[i][j] = V++; // 各試合にノードのIDを割り当てる
      }
    }
  }
  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < N - 1; j++)
    {
      A[i][j] = toId(i, A[i][j]); // i: 自分, j: 対戦相手, でIDに変換
    }
    for (int j = 1; j < N - 1; j++)
    {
      to[A[i][j]].push_back(A[i][j - 1]); // 入力のノード
    }
  }
  int ans = 0;
  for (int i = 0; i < V; i++)
  {
    int res = dfs(i);
    if (res == -1)
    {
      cout << -1 << endl;
      return 0;
    }
    ans = max(ans, res);
  }
  cout << ans << endl;
}

#include <bits/stdc++.h>
using namespace std;
#define debug(x) cout<<#x<<" = "<<(x)<<endl
#define debug2(x,y) cout<<"("<<#x<<","<<#y<<") = ("<<(x)<<","<<(y)<<")\n"
using vi = vector<int>;
using vvi = vector<vi>;
#define pb push_back
#define all(v) (v).begin(), (v).end()
#define vmin(v) *min_element(all(v))
#define vmax(v) *max_element(all(v))
#define rep(i, n) for(int i=0; i<(int)n; i++)

namespace /*DAG.cpp*/{
  int N,M; //頂点と辺の数
  vector<vector<int>> G; //グラフ
  vector<int> h; //入次数 : topoBFS
  vector<int> l_depth; //最大経路長 //recDFSでは探索済みかどうかも示す
  vector<int> s_depth; //最短経路長
  vector<int> ans; //答えを格納(recDFSではreverse必要)

  void input(){
    cin>>N>>M;
    G.resize(N);
    h.resize(N, 0);
    int f,t;
    for(int i=0; i<M; i++){
      cin>>f>>t;
      f--;t--;
      G[f].push_back(t); //recDFSとtopoBFS両方に必要
      h[t]++; //topoBFSにのみ必要
    }
  }

  void topoBFS(){
    l_depth.resize(N, -1);
    s_depth.resize(N, N);

    queue<int> unchecked;
    for(int i=0; i<N; i++){
      if(h[i]==0){
        unchecked.push(i);
        l_depth[i] = 0;
        s_depth[i] = 0;
      }
    }
    while(!unchecked.empty()){
      int current = unchecked.front();
      unchecked.pop();
      ans.push_back(current+1);
      for(int next: G[current]){
        h[next]--;

        l_depth[next] = max(l_depth[next], l_depth[current]+1); //最長経路長
        s_depth[next] = min(s_depth[next], s_depth[current]+1); //最短経路長

        if(h[next]==0){
          unchecked.push(next);
        }
      }
    }
  }

  void recDFS(int look){
    if(l_depth[look]!=-1) return;
    if(G[look].size()){
      for(int next: G[look]){
        recDFS(next);
        l_depth[look] = max(l_depth[next]+1, l_depth[look]);
        s_depth[look] = min(s_depth[next]+1, s_depth[look]);
      }
    }else{
      l_depth[look] = 0;
      s_depth[look] = 0;
    }
    ans.push_back(look+1);
  }
}

int main(){
  int n;
  cin>>n;
  vvi IDs(n, vi(n, -1));
  N = n*(n-1)/2;
  G.resize(N);
  h.resize(N, 0);

  int id = 0;
  for(int i=0; i<n; i++){
    for(int j=i+1; j<n; j++){
      IDs[i][j] = id;
      IDs[j][i] = id;
      id++;
    }
  }
  /*
  rep(i,n){
    rep(j,n){
      cout<<IDs[i][j]<<",";
    }
    cout<<endl;
  }
  debug(G.size());
  //*/
  int t, bufid, vsid;
  for(int i=0; i<n; i++){
    cin>>t;t--;
    bufid = IDs[i][t];
    for(int j=1; j<n-1; j++){
      cin>>t;t--;
      vsid = IDs[i][t];

      G[bufid].push_back(vsid);
      h[vsid]++;

      bufid = vsid;
    }
  }

  /*
  for(int i=0; i<N; i++){
    debug2(i, h[i]);
  }
  */

  topoBFS();
  /*
  for(int x: ans){
    cout<<x<<",";
  }cout<<" -> ";
  */
  bool isDAG = ans.size()==N;
  //cout<<(isDAG? "閉路なし": "閉路あり")<<endl;
  if(isDAG){
    int l_max = *max_element(l_depth.begin(), l_depth.end());
    cout<<l_max+1<<endl;
  }else{
    cout<<-1<<endl;
  }
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define REP(i,m,n) for(int i=(m);i<(n);i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
#define all(a) a.begin(),a.end()
#define rall(c) (c).rbegin(),(c).rend()
#define mp make_pair
#define endl '\n'
#define vec vector<ll>
#define mat vector<vector<ll> >
#define fi first
#define se second
typedef long long ll;
typedef pair<ll,ll> pll;
typedef long double ld;
const ll inf=1e9+7;
const ll mod=998244353;
signed main(){
    ll n;cin>>n;
    map<ll,vector<pll> >x,y;
    map<ll,vector<pll> >xpy;
    map<ll,vector<pll> >ymx;
    rep(i,n){
        ll a,b;cin>>a>>b;
        char c;cin>>c;
        ll d=0;
        if(c=='R')d=0;
        if(c=='U')d=1;
        if(c=='L')d=2;
        if(c=='D')d=3;

        x[a].pb(mp(b,d));
        y[b].pb(mp(a,d));
        xpy[a+b].pb(mp(a,d));
        ymx[b-a+200000].pb(mp(a,d));
    }
    ll ans=inf*inf;
    for(auto s:x){
        ll u=-1,d=-1;
        ll i=s.first;
        sort(all(x[i]));
        for(auto e:x[i]){
            if(e.second==1)d=e.first;
            if(e.second==3)u=e.first;
            if(u>=0&&d>=0&&u-d>=0){
                ans=min(ans,(u-d)*5);
            }
        }
    }
    for(auto s:y){
        ll l=-1,r=-1;
        ll i=s.first;
        sort(all(y[i]));
        for(auto e:y[i]){
            if(e.second==0)l=e.first;
            if(e.second==2)r=e.first;
            if(l>=0&&r>=0&&r-l>=0){
                ans=min(ans,(r-l)*5);
            }
        }
    }
    for(auto s:xpy){
        ll l=-1,r=-1,u=-1,d=-1;
        ll i=s.first;
        sort(all(xpy[i]));
        for(auto e:xpy[i]){
            if(e.second==0)l=e.first;
            if(e.second==2)r=e.first;
            if(e.second==1)d=e.first;
            if(e.second==3)u=e.first;
            if(l>=0&&d>=0&&d>=l)ans=min(ans,(d-l)*10);
            if(r>=0&&u>=0&&r>=u)ans=min(ans,(r-u)*10);
        }
    }
    for(auto s:ymx){
        ll l=-1,r=-1,u=-1,d=-1;
        ll i=s.first;
        sort(all(ymx[i]));
        for(auto e:ymx[i]){
            if(e.second==0)l=e.first;
            if(e.second==2)r=e.first;
            if(e.second==1)d=e.first;
            if(e.second==3)u=e.first;
            if(l>=0&&u>=0&&u>=l)ans=min(ans,(u-l)*10);
            if(r>=0&&d>=0&&r>=d)ans=min(ans,(r-d)*10);
        }
    }
    if(ans==inf*inf){
        cout<<"SAFE"<<endl;
    }else{
        cout<<ans<<endl;
    }
}

#line 2 "/Users/kaage/Desktop/ProgrammingWorkspace/library/other/template.hpp"
#define _CRT_SECURE_NO_WARNINGS
#pragma target("avx")
#pragma optimize("O3")
#pragma optimize("unroll-loops")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define all(V) V.begin(),V.end()
typedef long long lint;
typedef unsigned long long ulint;
typedef std::pair<int, int> P;
typedef std::pair<lint, lint> LP;
constexpr int INF = INT_MAX/2;
constexpr lint LINF = LLONG_MAX/2;
constexpr double eps = DBL_EPSILON;
constexpr double PI=3.141592653589793238462643383279;
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template <class T, class U>
inline bool chmax(T& lhs, const U& rhs) {
	if (lhs < rhs) {
		lhs = rhs;
		return 1;
	}
	return 0;
}
template <class T, class U>
inline bool chmin(T& lhs, const U& rhs) {
	if (lhs > rhs) {
		lhs = rhs;
		return 1;
	}
	return 0;
}
inline lint gcd(lint a, lint b) {
	while (b) {
		lint c = a;
		a = b; b = c % b;
	}
	return a;
}
inline lint lcm(lint a, lint b) {
	return a / gcd(a, b) * b;
}
bool isprime(lint n) {
	if (n == 1)return false;
	for (int i = 2; i * i <= n; i++) {
		if (n % i == 0)return false;
	}
	return true;
}
template<typename T>
T mypow(T a, lint b) {
	if (!b)return T(1);
	if (b & 1)return mypow(a, b - 1) * a;
	T memo = mypow(a, b >> 1);
	return memo * memo;
}
lint modpow(lint a, lint b, lint m) {
	if (!b)return 1;
	if (b & 1)return modpow(a, b - 1, m) * a % m;
	lint memo = modpow(a, b >> 1, m);
	return memo * memo % m;
}
template<typename T>
void printArray(std::vector<T>& vec) {
	rep(i, vec.size() - 1)std::cout << vec[i] << " ";
	std::cout << vec.back() << std::endl;
}
template<typename T>
void printArray(T l, T r) {
	T rprev = r;
	rprev--;
	for (T i = l; i != rprev; i++) {
		std::cout << *i << " ";
	}
	std::cout << *rprev << std::endl;
}
#line 2 "main.cpp"
int n,x[200010],y[200010];
char u[200010];
std::vector<std::pair<int,char>> vec[4][400010];
int main(){
	std::cin>>n;
	rep(i,n){
		std::cin>>x[i]>>y[i]>>u[i];
		vec[0][x[i]].emplace_back(y[i],u[i]);
		vec[1][y[i]].emplace_back(x[i],u[i]);
		vec[2][x[i]+y[i]].emplace_back(x[i],u[i]);
		vec[3][x[i]-y[i]+200000].emplace_back(x[i],u[i]);
	}
	rep(i,4){
		rep(j,400001)std::sort(all(vec[i][j]));
	}
	int ans=INF;
	rep(i,400001){
		int now=-1;
		for(const auto& j:vec[0][i]){
			if(j.second=='U')now=j.first;
			if(j.second=='D'&&now!=-1)chmin(ans,(j.first-now)*5);
		}
	}
	rep(i,400001){
		int now=-1;
		for(const auto& j:vec[1][i]){
			if(j.second=='R')now=j.first;
			if(j.second=='L'&&now!=-1)chmin(ans,(j.first-now)*5);
		}
	}
	rep(i,400001){
		int rnow=-1,dnow=-1;
		for(const auto& j:vec[2][i]){
			if(j.second=='R')rnow=j.first;
			if(j.second=='D')dnow=j.first;
			if(j.second=='U'&&rnow!=-1)chmin(ans,(j.first-rnow)*10);
			if(j.second=='L'&&dnow!=-1)chmin(ans,(j.first-dnow)*10);
		}
	}
	rep(i,400001){
		int rnow=-1,unow=-1;
		for(const auto& j:vec[3][i]){
			if(j.second=='R')rnow=j.first;
			if(j.second=='U')unow=j.first;
			if(j.second=='L'&&unow!=-1)chmin(ans,(j.first-unow)*10);
			if(j.second=='D'&&rnow!=-1)chmin(ans,(j.first-rnow)*10);
		}
	}
	if(ans==INF)puts("SAFE");
	else std::cout<<ans<<std::endl;
	return 0;
}


#include <iostream>
#include<cmath>

using namespace std;

int main()
{
    int n,i;
    cin>>n;
    double res;
    for(i=n; i>=1; i--)
    {
        res=pow(i,0.5);
        if(abs(res-int(res))==0)
        {
            cout<<i;
            return 0;
        }
    }
}

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

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

const ll mod=1000000007;

ll countBits(ll in){
  int res=0;
  for(;in>0;in>>=1){
    if((in&0x01)!=0){
      res++;
    }
  }
  return res;
}

template<typename T>
void show2dVector(vector<vector<T>>& v){
  for(int i=0;i<v.size();i++){
    int m=v[i].size();
    cout<<i<<" : ";
    for(int j=0;i<m;i++){
      cout<<v[i][j]<<" ";
    }
    cout<<endl;
  }
}

void bfs(const vector<vector<int>>&g, int v, vector<bool>& seen){
  seen[v]=true;
  cout<<v<<" ";
  for(auto next: g[v]){
    if(seen[next]){
      continue;
    }
    bfs(g,next,seen);
  }
}

bool dfs(vector<vector<int>> &g,int start,int goal,vector<bool>&seen){
  bool res=false;
  seen[start]=true;
  if(start==goal){
    return true;
  }
  for(auto next: g[start]){
    if(seen[next]){
      continue;
    }
    res=dfs(g,next,goal,seen);
    if(res){
      break;
    }
  }
  return res;
}

ll gcd(ll a,ll b) {
  return b? gcd(b,a%b): a;
}
ll lcm(ll a,ll b) {
  return a*b/gcd(a,b);
}
bool isLowerCase(char c){
  return (c>='a'&&c<='z');
}

char toLowerCase(char c){
  if(isLowerCase(c)){
    return c;
  }else{
    return c+'a'-'A';
  }
}
char toUpperCase(char c){
  if(isLowerCase(c)){
    return c-('a'-'A');
  }else{
    return c;
  }
}
ll powm(ll a,ll n, ll m){
  ll ret=1;
  while(n>0){
    if(n%2==1){
      ret=(ret*a)%m;
    }
    n>>=1;
    a=(a*a)%m;
  }
  return ret;
}

const string yesno(bool ans){
  return (ans?"Yes":"No");
}
int main() {
  string s;cin>>s;
  int w;cin>>w;
  for(int i=0;i<s.size();i+=w){
    cout<<s[i];
  }
  cout<<endl;
  return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>

using namespace std;

int main(){

	int N = 100000;

	bool a[100000];

	for(int i = 0; i < N; i++){
		a[i] = true;
	}

	a[0] = false;
	a[1] = false;

	for(int i = 2; i < N; i++){
		if(a[i]){
			for(int j = i * 2; j < N; j += i){
				a[j] = false;
			}
		}
	}

	int n;

	while(true){
		cin >> n;
		if(n == 0){
			break;
		}else if(n < 5 || n > 10000){
			printf("NA\n");
			continue;
		}else{
			for(int i = n; i > 2; i--){
				if(a[i] && a[i - 2]){
					printf("%d %d\n", i - 2, i);
					break;
				}
			}
		}
	}

	return 0;
}

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

#define gcu getchar_unlocked
#define pcu putchar_unlocked
#define _il inline
#define _in _il int in
#define _sc _il bool scan
_in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();
	do{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;} //&&c<='9'
_in() {return in(gcu());}
_sc(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}
_sc(char &c){c=gcu();gcu();return c!=EOF;}
//_sc(string &s){int c;s="";
//	for(;;){c=gcu();if(c=='\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}
template <typename H,typename... T> _sc(H &h, T&&... t){return scan(h)&&scan(t...);}
#define _vo _il void out
#define _vl _il void outl
template <typename T>
_vo(T n){static char buf[20];char *p=buf;
	if(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;
	while (p!=buf)pcu(*--p);}
_vo(const char *s){while(*s)pcu(*s++);}
_vo(char c){pcu(c);}
//_vo(string &s){for (char c: s) pcu(c);}
template <typename H,typename... T> _vo(H&& h, T&&... t){out(h);out(move(t)...);}
//template <typename T> _vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);out('\n');}
_vl(){out('\n');}
template <typename... T> _vl(T&&... t){out(move(t)...);outl();}

template<int N>
struct sieve {
	bool s[N];
	constexpr sieve() : s() {
		for (int i = 0; i < N; i++)
			s[i] = true;
		for (int i = 4; i < N; i += 2)
			s[i] = false;
		for (int i = 9; i < N; i += 6)
			s[i] = false;
		for (int i = 6, e = sqrt(N); i <= e; i += 6) {
			for (int j : {i - 1, i + 1})
				if (s[j])
					for (int k = j * j; k < N; k += j)
						s[k] = false;
		}
	}
};

template<int N>
struct twin {
	int t[N/10], l;
	constexpr twin() : t(), l(1) {
		sieve<N> s;
		t[0] = 5;
		for (int i = 0; i < N; i++)
			if (s.s[i - 2] && s.s[i])
				t[l++] = i;
	}
};

int main() {
	enum {N = 10001};
	twin<N> t;
	for (int n; (n = in());) {
		auto r = upper_bound(t.t, t.t + t.l, n) - 1;
		outl(*r - 2, ' ', *r);
	}
}


#include <iostream>
#include <bitset>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <regex>
#include <iomanip>
#include <climits>
#include <utility>
#include <queue>
using namespace std;
using ll = long long int;
using dd = long double;
const ll MOD = 1e9 + 7;
const dd PI = 3.1415926435;

class UnionFind
{
public:
    UnionFind(int N) : par(N)
    {
        for (ll i = 0; i < N; i++)
        {
            par[i] = i;
        }
    }

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

    void unite(int x, int y)
    {
        int rx = root(x);
        int ry = root(y);
        if (rx == ry)
            return;
        par[rx] = ry;
    }

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

private:
    vector<int> par;
};

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

ll fact(ll n)
{
    if (n == 0)
    {
        return 1;
    }
    if (n == 1)
    {
        return 1;
    }
    return n * fact(n - 1) % MOD;
}

ll pow_fast(ll n, ll k)
{
    if (k == 0)
    {
        return 1;
    }
    if (k == 1)
    {
        return n;
    }

    if (k % 2 == 0)
    {
        ll tmp = pow_fast(n, k / 2LL);
        return tmp * tmp % MOD;
    }
    else
    {
        ll tmp = pow_fast(n, k / 2LL);
        tmp *= tmp;
        tmp %= MOD;
        return tmp * n % MOD;
    }
}

map<ll, ll> sosuu(ll n)
{
    map<ll, ll> res;
    for (ll i = 2; i * i <= n; i++)
    {
        while (n % i == 0)
        {
            res[i] += 1;
            n /= i;
        }
    }
    if (n != 1)
    {
        res[n] += 1;
    }
    return res;
}

struct Dish{
    ll time;
    ll taste;
};
int main()
{
    ll N, T;
    cin >> N >> T;
    vector<Dish> dishes(N + 1);
    for (ll i = 0; i < N; i++)
    {
        ll ai, bi;
        cin >> ai >> bi;
        Dish d = {ai, bi};
        dishes[i + 1] = d;
    }

    vector<vector<ll>> DP1(N + 1, vector<ll>(T + 1, 0));
    vector<vector<ll>> DP2(N + 1, vector<ll>(T + 1, 0));

    // DP1 => 1-i 種類までの料理の中で j 分以内で最大の満腹度
    for (ll i = 1; i <= N; i++)
    {
        for (ll j = 0; j <= T; j++)
        {
            if (j < dishes[i].time) {
                DP1[i][j] = DP1[i - 1][j];
                continue;
            }
            DP1[i][j] = max(DP1[i - 1][j], dishes[i].taste + DP1[i - 1][j - dishes[i].time]);
        }
    }
    for (ll i = 1; i <= N; i++)
    {
        for (ll j = 0; j <= T; j++)
        {
            if (j < dishes[N - i + 1].time) {
                DP2[i][j] = DP2[i - 1][j];
                continue;
            }
            DP2[i][j] = max(DP2[i - 1][j], dishes[N - i + 1].taste + DP2[i - 1][j - dishes[N - i + 1].time]);
        }
    }

    ll ans = 0;
    for (ll i = 1; i <= N; i++)
    {
        for (ll j = 0; j <= T - 1; j++)
        {
            ans = max(ans, DP1[i - 1][j] + DP2[N - i][T - 1 - j] + dishes[i].taste);
        }
    }
    cout << ans << endl;
}

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

const int MAX_N  = 3009;
int N, T;
int A[MAX_N], B[MAX_N];
int dp[MAX_N][MAX_N];

void solve()
{
	vector<pair<int,int>> v;
	for(int i=0;i<N;++i) v.emplace_back(A[i],B[i]);
	sort(v.begin(),v.end());
	for(int i=0;i<N;++i){
		int ti = v[i].first, de = v[i].second;
		for(int t=0;t<=T;++t){
		    dp[i+1][t]=max(dp[i+1][t],dp[i][t]);
			if(t<T)dp[i+1][min(T,t+ti)]=max(dp[i+1][min(T,t+ti)], de+dp[i][t]);
		}
	}
	int ans = dp[N][T];
	cout<<ans;
}

int main()
{
	cin >> N >> T;
	for(int i=0;i<N;++i) cin >> A[i] >> B[i];
	solve();
	return 0;
}


#include <bits/stdc++.h>
using ll = long long;
using namespace std;
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for(int i = int(a); i < int(b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define all(x) (x).begin(), (x).end()
template <typename T> bool chmax(T &a, const T &b) {
    if(a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> bool chmin(T &a, const T &b) {
    if(a > b) {
        a = b;
        return 1;
    }
    return 0;
}
const long long INFLL = 1LL << 60;
const long long MOD = 1e9 + 7;

int main() {
    int N;
    cin >> N;
    ll sum = 0;
    rep(i, 1, N + 1) {
        if(i % 3 == 0 || i % 5 == 0) continue;
        sum += i;
    }
    cout << sum << endl;
}

#include <algorithm>
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using ll = long long;
using ld = long double;
#define endl "\n"
//#define int long long
#define ALL(x) begin(x),end(x)
#define _CRT_SECURE_NO_WARNINGS
#define rep(i, n) for (int i = 0; i < n; i++)
#define _GLIBCXX_DEBUG
const int MOD = 1e9 + 7;
const int INF = 1e18 + 9;
constexpr long double pi = 3.141592653589793238462643383279;
int fact(int i) {
    if (i == 0) return 1;
    return ((fact(i - 1)) * i) % MOD;
}
int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}
int lcm(int a, int b) {
    return a * b / gcd(a, b);
}
int keta(int n) {
    if (n == 0) return 1;
    int count = 0;
    while (n != 0) {
        n /= 10;
        count++;
    }
    return count;
}
int ketasum(int n) {
    int sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
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;
}
char toSmall(char c) { // 大文字を小文字へ
    return (c + 0x20);
}
char toLarge(char c) { // 小文字を大文字へ
    return (c - 0x20);
}
float myPower(int a, int n) { // aのn乗の計算
    float x = 1;
    while (n > 0) { // 全てのbitが捨てられるまで
        if (n & 1) { // 一番右のbitが１のとき
            x *= a;
        }
        a *= a;
        n >>= 1; // bit全体を右に1つシフトして一番右を捨てる
    }
    return x;
}
bool is_prime(const unsigned n) {
    switch (n) {
    case 0: // fall-through
    case 1: return false;
    case 2: // fall-through
    case 3: return true;
    } // n > 3 が保証された
    if (n % 2 == 0 || n % 3 == 0) return false;
    // n は 2 と 3 のいずれの倍数でもないことが保証された
    // これより n は (6の倍数)-1 か (6の倍数)+1 である
    // 6の倍数前後の数を使って試し割りをする
    for (unsigned i = 5; i * i <= n; i += 6) {
        if (n % i == 0) return false; // (6の倍数)-1
        if (n % (i + 2) == 0) return false; // (6の倍数)+1
    }
    return true;
}

/*signed*/int main(void) {
    string s;
    cin >> s;
    int n;
    cin >> n;
    for (int i = 0; i < s.size(); i = i + n) {
        cout << s[i];
    }
    cout << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int D,K;
  cin>>K>>D;
  //vector<int>ans;
  for(int k=K;k>1;k--){
    cout<<D-k+1<<" ";
  }
  cout<<D<<" ";
  for(int k=1;k<K;k++){
    cout<<D+k<<" ";
  }

}

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

template<typename T, typename Q>
istream &operator>>(istream &is, pair<T, Q> &p) {
	return is >> p.first >> p.second;
}

template<typename T>
istream &operator>>(istream &is, vector<T> &v) {
	for (auto &x : v) is >> x;
	return is;
}

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

template<typename T>
ostream &operator<<(ostream &os, vector<T> v) {
	os << "[";
	for (auto it = v.begin(); it != v.end(); it++)
		os << (it == v.begin() ? "" : ", ") << *it;
	return os << "]";
}

template<typename T, typename Q>
ostream &operator<<(ostream &os, map<T, Q> m) {
	os << "[";
	for (auto it = m.begin(); it != m.end(); it++)
		os << (it == m.begin() ? "" : ", ") << *it;
	return os;
}
#define imie(...) " [" << #__VA_ARGS__": " << (__VA_ARGS__) << "] "

int main() {
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int mn = -1000000;
	int k, x; cin >> k >> x;
	set<int> s;
	if (x - k + 1 < mn) {
		for (int i = mn; i <= mn + k - 1; i++) {
			s.insert(i);
		}
		for (int i = x; i <= x + k - 1; i++) {
			s.insert(i);
		}
	} else if (x + k - 1 > -mn) {
		for (int i = -mn; i >= -mn - k + 1; i--) {
			s.insert(i);
		}
		for (int i = x; i >= x - k + 1; i--) {
			s.insert(i);
		}
	} else {
		for (int i = x; i <= x + k - 1; i++) {
			s.insert(i);
		}
		for (int i = x; i >= x - k + 1; i--) {
			s.insert(i);
	 	}
	}
	for (auto x : s) cout << x << " ";
}


#include <cstdio>

const int maxn = 1e6 + 10;

int n, fnt, rar, q[maxn], ans, i, j;
char s[maxn], t[maxn];

int main() {
	scanf("%d%s%s", &n, s + 1, t + 1);
	j = 1;
	for (i = 1; i <= n; ++i) {
		if(s[i] != t[i]) {
			j = 0;
			break;
		}
	}
	if(j) {
		return !puts("0");
	}
	j = n + 1;
	for (i = n; i; --i) {
		if(!(j - 1 >= i && t[j - 1] == s[i])) {
			continue;
		}
		while(j - 1 >= i && t[j - 1] == s[i]) {
			--j;
		}
		while(fnt < rar && q[fnt] - rar + fnt >= j) {
			++fnt;
		}
		if(i < j) {
			q[rar++] = i;
			(rar - fnt > ans) && (ans = rar - fnt);
		}
	}
	return !printf("%d\n", j == 1 ? ans + 1 : -1);
}

//khodaya khodet komak kon
#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define all(x) x.begin(), x.end()
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")

using namespace std;

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

const int N = 1000000 + 10;
const ll MOD = 1000000000 + 7;
const ll INF = 1000000010;
const ll LOG = 25;

int n, Ans;
char S[N], T[N];
int bias, que[N], head, tail;

int main() {
	cin >> n;
	for (int i = 1; i <= n;i++) cin >> S[i];
	for (int i = 1; i <= n; i++) cin >> T[i];
	int ok = 1;
	for (int i = 1; i <= n; ++i) if (S[i] != T[i]) ok = 0;
	if (ok) return cout << 0, 0;
	head = 1, tail = 0;
	for (int i = n, j = n; i >= 1; --i) {
		if (j > i) j = i;
		while (head <= tail && que[head] + bias > i) ++head;
		Ans = std::max(Ans, tail - head + 2);
		if (i == 1 || T[i - 1] != T[i]) {
			while (j && S[j] != T[i]) --j;
			if (!j) return cout << -1, 0;
			--bias;
			que[++tail] = j - bias;
			--j;
		}
	}
	cout << Ans;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100000+10;
int n,m,a[maxn],ans[maxn],res[maxn],tmp[maxn];
long long k;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;++i)scanf("%d",a+i);
    for(int i=1;i<n;++i)ans[i]=i;
    scanf("%d%lld",&m,&k);
    for(int i=1;i<=m;++i){
        int x;
        scanf("%d",&x);
        swap(ans[x],ans[x-1]);
    }
    for(int i=1;i<n;++i)res[i]=i;
    while(k){
        if(k&1)
            for(int i=1;i<n;++i)res[i]=ans[res[i]];
        for(int i=1;i<n;++i)tmp[i]=ans[ans[i]];
        for(int i=1;i<n;++i)ans[i]=tmp[i];
        k>>=1;
    }
    long long sum=a[1];
    for(int i=1;i<=n;++i){
        printf("%lld.0\n",sum);
        sum+=a[res[i]+1]-a[res[i]];
    }
}

#include <stdio.h>
#include <algorithm>
#include <assert.h>
#include <bitset>
#include <cmath>
#include <complex>
#include <deque>
#include <functional>
#include <iostream>
#include <limits.h>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define ll long long
#define rep2(i,a,b) for(ll i=a;i<=b;++i)
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep3(i,a,b) for(ll i=a;i>=b;i--)
#define REP(e,v) for(auto e:v)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define tii tuple<int,int,int>
#define pq priority_queue<int>
#define pqg priority_queue<int,vector<int>,greater<int>>
#define pb push_back
#define edge(v,a,b) v[a].pb(b);v[b].pb(a);
#define MAX_V 400010
#define vec vector<int>
#define vecll vector<ll>
#define vecpii vector<pii>
#define endl "\n"
#define ALL(c) (c).begin(),(c).end()
using namespace std;
int in() {int x;scanf("%d",&x);return x;}
ll lin() {ll x;scanf("%lld",&x);return x;}
void makegraph(int x,vector<vec> &v){rep(i,x-1){int a=in(),b=in();v[a].pb(b);v[b].pb(a);}}
template<typename A, size_t NNN, typename T>
void Fill(A (&array)[NNN], const T &val){
    fill( (T*)array, (T*)(array+NNN), val );
}
#define INF 1e9+7
#define LLINF 1e18+7
ll MOD=1e9+7;
#define N 255050

ll n,m,k;
ll a[N],x[N];
int mv[80][N];

main(){
    n=in();
    rep(i,n)x[i]=in();
    m=in();
    k=lin();
    rep(i,m)a[i]=in();
    rep(i,n-1)mv[0][i]=i;
    rep(i,m)swap(mv[0][a[i]-1],mv[0][a[i]-2]);
    rep(i,63){
        rep(j,n-1){
            mv[i+1][j]=mv[i][mv[i][j]];
        }
    }
    /*
    rep(i,3){
        rep(j,n)cout<<mv[i][j]<<" ";
        cout<<endl;
    }
    */
    vec now(n),temp(n);
    rep(i,n-1)now[i]=i;
    rep(i,63){
        if(k&(1ll<<i)){
            rep(j,n-1){
                temp[j]=now[mv[i][j]];
                /*printf("mv[i][j]=%d now[mv[i][j]]=%d\n",mv[i][j],now[mv[i][j]]);
                */
            }
            /*cout<<"now="<<i<<endl;
            rep(ii,n-1)cout<<temp[i]<<" ";
            cout<<endl;
            */
            now=temp;
        }
    }
    /*
    rep(i,n-1)cout<<now[i]<<" ";
    cout<<endl;
    */
    vec d(n);
    rep(i,n-1)d[i]=x[i+1]-x[i];
    /*
    rep(i,n-1)cout<<d[i]<<" ";
    */
    cout<<x[0]<<endl;
    rep(i,n-1){
        x[i+1]=x[i]+d[now[i]];
        cout<<x[i+1]<<endl;
    }
}


#include <bits/stdc++.h>
#define rep(i,n) for (int (i) = 0; (i) < (n); i++)
#define ll long long
using namespace std;
int main() {
  ll N = 0, A,B;;
  cin >> N >> A >> B;
  if(N == 1){
    cout << "Hello World";
  }
  else{
    cout << A + B;
  }
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <queue>
#include <algorithm>

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

using namespace std;
typedef long long LL;

int main(int argc, char* argv[]){
	cin.tie(0);
	ios::sync_with_stdio(false);

	string A, B, C;
	cin >> A >> B >> C;
	if(A[A.size()-1] == B[0] && B[B.size()-1] == C[0]){
		printf("YES\n");
	}
	else{
		printf("NO\n");
	}
	return 0;
}


#include <iostream>
#include<vector>
using namespace std;
typedef long long ll;
int main() {
	int n;cin>>n;
	ll d;cin>>d;
	vector<ll> a(n);
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	vector<ll> r(n);
	r[n-1]=n-1;
	for(int i=n-2;i>=0;i--){
		if(a[r[i+1]]+(r[i+1]-i)*d>a[i]){
			r[i]=i;
		}else{
			r[i]=r[i+1];
		}
	}
	int ri=0;
	ll ra=a[0];
	ll ans=0;
	while(ri!=n-1){
		ans+=ra+a[r[ri+1]]+(r[ri+1]-ri)*d;
		for(int i=ri+1;i<r[ri+1];i++){
			if((i-ri)*d+ra<(r[ri+1]-i)*d+a[r[ri+1]]){
				ans+=a[i]+ra+(i-ri)*d;
			}else{
				ans+=a[i]+(r[ri+1]-i)*d+a[r[ri+1]];
			}
		}
		ra+=(r[ri+1]-ri)*d;
		if(ra>a[r[ri+1]]){
			ra=a[r[ri+1]];
		}
		ri=r[ri+1];
	}
	cout<<ans<<endl;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int (i) = (a); (i) < (b); ++(i))
#define per(i, a, b) for (int (i) = (a); (i) >= (b); --(i))
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define eb emplace_back
#define ff first
#define ss second
#define sz(x) ((int) x.size())
#define rd(type, ...) type __VA_ARGS__; sc(__VA_ARGS__)
#define rda(a, n) rep(i, 0, n) cin >> a[i];
#define rdaa(a, n, m) rep(i, 0, n) rep(j, 0, m) cin >> a[i][j];
#define rdv(type, v, n) vector<type> v(n); rep(__ii, 0, n) cin >> v[__ii]
#define rdm(type, v, h, w) vector<vector<type>>(h, vector<type>(w)) v; rep(__ii, 0, h) rep(__jj, 0, w) cin >> v[__ii][__jj]
#define rdv2(type, n, ...)std::vector<type> __VA_ARGS__;MACRO_rdv2_Init(n, __VA_ARGS__); for(int w_=0; w_<n; ++w_){MACRO_rdv2_Scan(w_, __VA_ARGS__);}
#define dbg(...) cerr << "[" << #__VA_ARGS__ << "] : ", debug_out(__VA_ARGS__)
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
void solve();
signed main() {ios::sync_with_stdio(false); cin.tie(0);
  cout << fixed; cout.precision(20); solve(); return 0;}
template<typename T> void chmin(T &a, T b) {if (a > b) a = b;}
template<typename T> void chmax(T &a, T b) {if (a < b) a = b;}
template<typename T> void MACRO_rdv2_Init(int n, T& t) { t.resize(n); }
template<typename First, typename... Rest> void MACRO_rdv2_Init(int n, First& first, Rest& ...rest) { first.resize(n); MACRO_rdv2_Init(n, rest...); }
template<typename T> void MACRO_rdv2_Scan(int p, T& t) { std::cin >> t[p]; }
template<typename First, typename... Rest> void MACRO_rdv2_Scan(int p, First& first, Rest& ...rest) { std::cin >> first[p]; MACRO_rdv2_Scan(p, rest...); }
template<typename T> void wrv(const vector<T> &v) {rep(__ii, 0, sz(v)) {if (__ii) cout << ' '; cout << v[__ii];} cout << '\n';}
template<typename T> void wrm(const vector<vector<T>> &v) {rep(__ii, 0, sz(v)) {rep(__jj, 0, v[__ii].size()) {if (__jj) cout << ' '; cout << v[__ii][__jj];} cout << '\n';}}
template<typename T> void sc(T& x) {cin >> x;}
template<typename Head, typename... Tail> void sc(Head& head, Tail&... tail) {cin >> head; sc(tail...);}
template<typename T> void wr(const T& x) {cout << x << '\n';}
template<typename Head, typename... Tail> void wr(const Head& head, const Tail&... tail) {cout << head << ' '; wr(tail...);}
template<typename T> void wrf(const T& x) {cout << x << endl;}
template<typename Head, typename... Tail> void wrf(const Head& head, const Tail&... tail) {cout << head << ' '; wrf(tail...);}
template<typename T> void debug_out(const T& x) {cerr << x << '\n';}
template<typename Head, typename... Tail> void debug_out(const Head& head, const Tail&... tail) {cerr << head << ' '; debug_out(tail...);}
template<typename... T> void err(const T&... cod) {wr(cod...); exit(0);}

const int N = 305;

string s;
int n, k;
int dp[N][N][N];

int f(int l, int r, int sisa) {
  if (l > r) return 0;
  if (l == r) return 1;
  if (dp[l][r][sisa] != -1) return dp[l][r][sisa];

  int ans = 2 * (s[l] == s[r]) + f(l + 1, r - 1, sisa);
  if (sisa > 0) chmax(ans, 2 + f(l + 1, r - 1, sisa - 1));
  chmax(ans, f(l + 1, r, sisa));
  chmax(ans, f(l, r - 1, sisa));

  return dp[l][r][sisa] = ans;
}

void solve() {
  cin >> s >> k;
  n = sz(s);
  memset(dp, -1, sizeof dp);
  wr(f(0, n - 1, k));
}


//#define _GLIBCXX_DEBUG
#include<bits/stdc++.h>
#define PI 3.14159265359
using namespace std;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
const long long INF= 1e+18+1;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vector<ll> >vvl;
typedef pair<ll,ll> P;
typedef tuple<ll,ll,ll> T;
const ll MOD=1000000007LL;
string abc="abcdefghijklmnopqrstuvwxyz";
string ABC="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//素数判定O(√n)
bool is_prime(ll n){
  for(ll i=2;i*i<=n;i++){
    if(n%i==0)return false;
  }
  return n!=1;
}
int main(){
  ll n;cin>>n;
  vl vec;
  ll i=1;
  while(true){
    ll k=5*i+1;
    if(is_prime(k))vec.push_back(k);
    if(vec.size()==n)break;
    i++;
  }
  rep(i,n-1){
    cout<<vec[i]<<" ";
  }
  cout<<vec[n-1]<<endl;
}

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>

typedef unsigned long long ULLONG;
typedef long long LLONG;
static const LLONG MOD_NUM = 1000000007;

template<class _T> static void getint(_T& a) {
	const char* fmt = " %d";
	if (sizeof(_T) == sizeof(long long)) {
		fmt = " %lld";
	}

	if (scanf(fmt, &a) < 0) {
		printf("g1int Error\n");
	}
}
template<class _T> static void getint(_T& a, _T& b) {
	const char* fmt = " %d %d";
	if (sizeof(_T) == sizeof(long long)) {
		fmt = " %lld %lld";
	}

	if (scanf(fmt, &a, &b) < 0) {
		printf("g2int Error\n");
	}
}
template<class _T> static void getint(_T& a, _T& b, _T& c) {
	const char* fmt = " %d %d %d";
	if (sizeof(_T) == sizeof(long long)) {
		fmt = " %lld %lld %lld";
	}

	if (scanf(fmt, &a, &b, &c) < 0) {
		printf("g3int Error\n");
	}
}

static void ABC096D();

#if 1
int main()
{
	ABC096D();
	fflush(stdout);
	return 0;
}
#endif

template <class _T> void tp_getPrimes(_T targ, std::map<_T, _T>& primes)
{
	_T target = targ;
	_T i = 2;
	while ((i * i) <= target) {
		if ((target % i) == 0) {
			target /= i;
			primes[i]++;
		}
		else {
			i++;
		}
	}
	if (target > 1) {
		primes[target]++;
	}
}

static void ABC096D()
{
	int N;
	getint(N);

	int count = 0;
	std::vector<int> primeNumbers;
	for (int i = 2; (i <= 55555) && (count < N); i++) {
		std::map<int, int> primes;
		tp_getPrimes<int>(i, primes);
		if ((primes.size() == 1) && (primes.begin()->second == 1)) {
			if (primes.begin()->first % 5 == 1) {
				primeNumbers.push_back(primes.begin()->first);
				count++;
			}
		}
	}

	std::string str;
	for (int i = 0; i < N; i++) {
		char tmp[16] = { 0 };
		sprintf(tmp, "%d", primeNumbers[i]);

		if (i) {
			str += ' ';
		}
		str += tmp;
	}
	printf("%s\n", str.c_str());
}


#include <bits/stdc++.h>
#include <atcoder/all>
#define rep(i,n) for(int i=(0);i<(n);i++)

using namespace std;
using namespace atcoder;

typedef long long ll;

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

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

	int n, q;
	cin >> n >> q;

	vector<ll> a(n);
	rep(i, n) cin >> a[i];

	fenwick_tree<ll> fw(n);
	rep(i, n) fw.add(i, a[i]);

	rep(i, q){
		int t;
		cin >> t;

		if(t == 0){
			ll p, x;
			cin >> p >> x;
			fw.add(p, x);
		}else{
			ll l, r;
			cin >> l >> r;
			cout << fw.sum(l, r) << endl;
		}
	}

}

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

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

    int k=m*2+1;
    // first part
    for ( int l=1,r=m; l<r; l++,r-- ) {
        cout << l << ' ' << r << '\n';
    }
    for ( int l=m+1,r=k; l<r; l++,r-- ) {
        cout << l << ' ' << r << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long
#define ls id << 1
#define rs id << 1 | 1
#define mem(array, value, size, type) memset(array, value, ((size) + 5) * sizeof(type))
#define memarray(array, value) memset(array, value, sizeof(array))
#define fillarray(array, value, begin, end) fill((array) + (begin), (array) + (end) + 1, value)
#define fillvector(v, value) fill((v).begin(), (v).end(), value)
#define pb(x) push_back(x)
#define st(x) (1LL << (x))
#define pii pair<int, int>
#define mp(a, b) make_pair((a), (b))
#define Flush fflush(stdout)
#define vecfirst (*vec.begin())
#define veclast (*vec.rbegin())
#define vecall(v) (v).begin(), (v).end()
#define vecupsort(v) (sort((v).begin(), (v).end()))
#define vecdownsort(v, type) (sort(vecall(v), greater<type>()))
#define veccmpsort(v, cmp) (sort(vecall(v), cmp))
using namespace std;
const int N = 500050;
const int inf = 0x3f3f3f3f;
const ll llinf = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
const int MOD = 1e9 + 7;
const double PI = acos(-1.0);
clock_t TIME__START, TIME__END;
void program_end()
{
#ifdef ONLINE
    printf("\nTime used: %.6lf(s)\n", ((double)TIME__END - TIME__START) / 1000);
    system("pause");
#endif
}
int h, w;
int A[N], B[N], cnt[N];
map<int, int> c;

inline void solve()
{
    scanf("%d%d", &h, &w);
    for (int i = 1; i <= h; ++i)
        scanf("%d%d", &A[i], &B[i]);
    for (int i = 1; i <= w; ++i)
        c.insert(mp(i, i));
    int ans = 0;
    cnt[0] = w;
    for (int i = 1; i <= h; ++i)
    {
        int L = A[i], R = B[i];
        auto it = c.lower_bound(L);
        int pos = 0;
        while (it != c.end() && it->first <= R + 1)
        {
            pos = max(pos, it->second);
            cnt[it->first - it->second]--;
            it = c.erase(it);
        }
        if (pos && R + 1 <= w)
        {
            cnt[R + 1 - pos]++;
            c.insert(mp(R + 1, pos));
        }
        while (!cnt[ans] && ans < w)
            ans++;
        if (ans == w)
            puts("-1");
        else
            printf("%d\n", ans + i);
    }
}

int main()
{
    TIME__START = clock();
    int Test = 1;
    // scanf("%d", &Test);
    while (Test--)
        solve();
    TIME__END = clock();
    program_end();
    return 0;
}

#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef vector<double> Vec;
typedef vector<Vec> Mat;
typedef pair<ll,ll> P;
typedef pair<double,ll> Pd;
typedef pair<double,double> PD;
typedef priority_queue<P,vector<P>,greater<P> > P_queue;
typedef priority_queue<Pd,vector<Pd>,greater<Pd> > Pd_queue;

const ll MOD=998244353;
const ll mod=1000000007;
const ll INF=1e15;
const double DEL=1e-6;

#define _GLIBCXX_DEBUG
#define REP(i,a,b) for(int i=(int)a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
#define mp make_pair
#define ALL(a) a.begin(),a.end()
#define U_ERASE(V) V.erase(unique(ALL(V)), V.end())

void Add(ll &a, ll b){
    a=(a+b)%mod;
    return;
}

void Pro(ll &a, ll b){
    a=(a*b)%mod;
    return;
}

ll H,W;
vector<P> d;

vec ans;
void init(){
    cin>>H>>W;
    rep(i,H){
        ll x,y; cin>>x>>y;
        x--; y--;
        d.pb(mp(x,y));
        ans.pb(-1);
    }
}

void Solve(){
    set<P> x;
    multiset<ll> y;
    rep(i,W) {
        P f=mp(i,i);
        x.insert(f);
        y.insert(0);
    }
    rep(i,H){
        ll Biggest=-INF;
        for(auto itr=x.lower_bound(mp(d[i].first,-INF));itr!=x.end();){
            ll R=(*itr).first, L=(*itr).second;
           // cout<<i<<':'<<R<<' '<<L<<endl;
            if(R>d[i].second+1) break;
            Biggest=max(Biggest,L);
            auto itr1=y.lower_bound(R-L);
            y.erase(itr1);
            itr=x.erase(itr);
        }
        if(Biggest!=-INF) if(d[i].second!=W-1) {x.insert(mp(d[i].second+1,Biggest)); y.insert(d[i].second+1-Biggest);}
        if(y.size()) ans[i]=*(y.begin());
        else break;
    }
    rep(i,H) if(ans[i]>=0) ans[i]+=(i+1);

}

int main(){
    init();
    Solve();
    rep(i,H) cout<<ans[i]<<endl;
}


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

int main() {
	string cipher;

	while (getline(cin, cipher)) {
		for (int i = 0; i < 26;i++) {
			for (unsigned int n = 0;n < cipher.length();n++) {
				if (cipher.at(n) == 'z') {
					cipher.at(n) = 'a';
				}
				else if (cipher.at(n) >= 'a'&&cipher.at(n) <= 'y') {
					cipher.at(n)++;
				}
			}

			if (cipher.find("the") != string::npos ||
				cipher.find("this") != string::npos ||
				cipher.find("that") != string::npos) {
				cout << cipher << endl;
			}
		}
	}

	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;

#define rep(i,n) for(ll i=0;i<n;i++)
#define REP(i,a,n) for(ll i=a;i<n;i++)

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef tuple<int,int,int> tiii;
typedef pair<ll, ll> pll;

const int INF = 100000000;
const ll LINF = 1e18+5;

ll A[200000];
ll B[200000];
ll C[200000];
ll D[400000];
//ll T[200000];

int main() {
    ll N;
    cin >> N;
    rep(i,N) cin >> A[i];
    rep(i,N) cin >> B[i];
    rep(i,N) {
        C[i] = A[i] ^ A[(i+1)%N];
        D[i] = B[i] ^ B[(i+1)%N];
        D[i+N] = D[i];
    }
    ll pos = 0;
    ll wpos = 0;

    // T構築
    /*ll tpos = 2;
    ll twpos = -1;
    T[0] = -1;
    T[1] = 0;
    while(tpos < N) {
        if (C[tpos-1] == C[twpos]) {
            T[tpos] = twpos + 1;
            tpos++;
            twpos++;
        } else if (twpos > 0) {
            twpos = T[twpos];
        } else {
            T[tpos] = 0;
            tpos++;
        }
    }*/

    vector<int> T(N+1);
    T[0] = -1;
    int j = -1;
    for (int i = 0; i < N; i++) {
        while (j >= 0 && C[i] != C[j]) j = T[j];
        T[i+1] = ++j;
    }

    vector<ll> Ks;

    while(pos + wpos < 2*N-1) {
        if(C[wpos] == D[pos+wpos]) {
            wpos++;
            if(wpos == N) {
                Ks.push_back((N-pos)%N);
                pos = pos + wpos - T[wpos];
                wpos = T[wpos];
            }
        } else {
            pos = pos + wpos - T[wpos];
            if(wpos > 0) wpos = T[wpos];
        }
    }
    sort(Ks.begin(), Ks.end());
    for(auto k : Ks) {
        ll x = B[0] ^ A[k];
        cout << k << " " << x << endl;
    }
    return 0;
}

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

struct Answer
{
	int m;
	vector<int> G;
	int cnt;
};

void insertionSort(vector<int> &A, int &g, int &cnt)
{
	for(int i = g; i < A.size(); i++){
		int v = A[i];
		int j = i - g;
		while(j >= 0 && A[j] > v){
			A[j+g] = A[j];
			j = j - g;
			cnt++;
		}
		A[j+g] = v;
	}
}

vector<int> FindShellSortNumber(int n)
{
	int g = 1;
	vector<int> G;
	while(g <= n){
		G.push_back(g);
		g = 3 * g + 1;
	}
	int size = G.size();
	for(int i = 1; i <= size / 2; i++){
		swap(G[i-1], G[size-i]);
	}
	return G;
}

Answer shellSort(vector<int> &A)
{
	Answer Result;
	Result.cnt = 0;
	Result.G   = FindShellSortNumber(A.size());
	Result.m   = Result.G.size();
	for(int i = 0; i < Result.m; i++){
		insertionSort(A, Result.G[i], Result.cnt);
	}
	return Result;
}

int main()
{
	int n;
	cin >> n;
	vector<int> A;
	A.resize(n);
	for(int i = 0; i < n; i++){
		cin >> A[i];
	}
	Answer Result = shellSort(A);
	cout << Result.m << endl;
	for(int i = 0; i < Result.G.size() - 1; i++){
		cout << Result.G[i] << ' ';
	}
	cout << Result.G[Result.G.size() - 1] << endl;
	cout << Result.cnt << endl;
	for(int i = 0; i < A.size(); i++){
		cout << A[i] << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
#define TOP 0
#define FRONT 1
#define LEFT 2
#define RIGHT 3
#define BACK 4
#define BOTTOM 5
using namespace std;

//TOP,FRONT,LEFT,RIGHT,BACK,BOTTOM
int dice[6]={1,2,4,3,5,6};

void rotN(){
  swap(dice[TOP],dice[FRONT]);
  swap(dice[FRONT],dice[BOTTOM]);
  swap(dice[BOTTOM],dice[BACK]);
}

void rotS(){rotN(),rotN(),rotN();}

void rotE(){
  swap(dice[TOP],dice[LEFT]);
  swap(dice[LEFT],dice[BOTTOM]);
  swap(dice[BOTTOM],dice[RIGHT]);
}

void rotW(){rotE(),rotE(),rotE();}

void rotCW(){
  swap(dice[FRONT],dice[RIGHT]);
  swap(dice[RIGHT],dice[BACK]);
  swap(dice[BACK],dice[LEFT]);
}

void rotCCW(){rotCW(),rotCW(),rotCW();}

int main(){
  cin>>dice[TOP]>>dice[FRONT]>>dice[RIGHT];
  cin>>dice[LEFT]>>dice[BACK]>>dice[BOTTOM];

  string str;
  cin>>str;
  for(int i=0;i<str.size();i++){
    if(str[i]=='N') rotN();
    if(str[i]=='S') rotS();
    if(str[i]=='E') rotE();
    if(str[i]=='W') rotW();
  }

  cout << dice[TOP]<<endl;

}

#include <bits/stdc++.h>
#include<math.h>
#include<algorithm>
#define rep(i,n) for (int i = 0; i < (n) ; ++i)
using namespace std;
using ll = long long ;
using P = pair<int, int> ;
#define PI 3.14159265358979323846264338327950
#define INF 1e18
#define mod 1000000007
ll gcd (ll x, ll y){
	ll r = x % y ;
	if(r == 0) return y ;
	return gcd(y, r) ;
}
bool isprime(ll x){
	ll s = sqrt((double) x) ;
	for(ll i = 2; i <= s ; i++){
		if(x % i == 0) return false ;
	}
	return true ;
}
int main (){
	ll a, b ;
	cin >> a >> b ;
	ll k = gcd(a, b) ;
	ll s = sqrt((double)k) ;
	vector<ll> y ;
	for(ll i = 1; i <= s; i++){
		if(k % i == 0){
			y.push_back(i) ;
			if(i != k/i){
				y.push_back(k/i) ;
			}
		}
	}
	sort(y.begin(), y.end()) ;
	ll num = y.size() ;
	ll ans = 0 ;
	rep(i, num){
		if(isprime(y[i])) ans++ ;
	}
	cout << ans << endl ;
}


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

int main() {
  int A, B;
  cin >> A >> B;

  int sum = 0;

  for (int i = A; i <= B; i++) {
    int x = i;
    int n1 = x % 10;
    x = x / 10;
    int n2 = x % 10;
    x = x / 10;
    //int n3 = x % 10;
    x = x / 10;
    int n4 = x % 10;
    x = x / 10;
    int n5 = x;

    if (n1 == n5 && n2 == n4) {
      sum++;
    }
  }
  cout << sum << endl;
}

#include <iostream>
using namespace std;

int main()
{
  int r;
  int g;
  //int ans;

  cin >> r;
  cin >> g;
  cout << 2 * g - r << endl;
}


#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <bitset>
#include <math.h>

typedef long long ll;
typedef unsigned long long ull;

#define vi std::vector<int>
#define vl std::vector<ll>
#define floop(n) for(int i = 0; i < n; ++i)
#define print(x) std::cout << x << std::endl;

const ll INF = 1e18;

int main()
{
    int A, B;
    std::cin >> A >> B;

    print(A*B);
    return 0;
}

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

set<int> numbers;
int n, k, cards[10], used[10];

void addcard(int x, int y){
  if(x == 0){
    numbers.insert(y);
  }
  for(int i = 0;i < n;i++){
    if(used[i] == 0){
      int shift = 10;
      if(cards[i] >= 10)shift *= 10;
      used[i] = 1;
      addcard(x - 1, y * shift + cards[i]);
      used[i] = 0;
    }
  }
}

int main(){
  while(1){
    numbers.clear();
    scanf("%d%d", &n, &k);
    if(n == 0 && k == 0)return 0;
    for(int i = 0;i < n;i++){
      used[i] = 0;
      scanf("%d", cards + i);
    }
    addcard(k, 0);
    printf("%d\n", numbers.size());
  }
}


#include<stdio.h>
#define ll long long

int main(){
	ll n, rev, i = 0;
	scanf("%lld", &n);
	char str[100];
	while(n){
		if(n == 0){
			break;
		}
		n--;
		rev = n % 26;
		n /= 26;
		str[i] = 'a' + rev;
		i++;
	}
	for(ll j = i - 1; j >= 0; j--){
		printf("%c", str[j]);
	}
	puts("");
	return 0;
}

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

int main(){
  long long N;
  cin >> N;
  string S="";
  while(N){
    N--;
    int A=N%26;
    N/=26;
    char a='a'+A;
    S.push_back(a);
  }
  reverse(S.begin(),S.end());
  cout << S << endl;
}


#include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 1000000000000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

#define SIZE 12

char A[SIZE],B[SIZE],C[SIZE];

int main(){

	scanf("%s %s %s",A,B,C);

	char last_a,last_b;
	for(int i = 0; A[i] != '\0'; i++){

		last_a = A[i];
	}
	for(int i = 0; B[i] != '\0'; i++){

		last_b = B[i];
	}

	if(last_a == B[0] && last_b == C[0]){

		printf("YES\n");

	}else{

		printf("NO\n");
	}

	return 0;
}

#include <iostream>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include <queue>
#include <math.h>
#include <stack>
#include <set>
#include <deque>
#include <cmath>

using namespace std;
typedef long long ll;
ll mod = 1e9+7;
//ll mod = 998244353;
#define rep(i,n) for(int i = 0; i < (n); ++i)

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


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

struct data {
  string l;
  int p, a, b, c, d, e, f, s, m;
};

int n;
vector<data> v;

bool ch(data l, data r);
void solve();
double calc(data now);

int main() {
  while(1) {
    cin >> n;
    if(n == 0) break;
    for(int i = 0; i < n; ++i) {
      data now;
      cin >> now.l >> now.p >> now.a >> now.b >> now.c >>
          now.d >> now.e >> now.f >> now.s >> now.m;
      v.push_back(now);
    }
    solve();
    for(int i = 0; i < n; ++i) cout << v[i].l << endl;
    cout << "#" << endl;
    v.erase(v.begin(), v.end());
  }
  return 0;
}

bool ch(data l, data r) {
  double nowl = calc(l), nowr = calc(r);
  if(nowl != nowr) return nowl > nowr;
  return l.l < r.l;
}

void solve() { sort(v.begin(), v.end(), ch); }

double calc(data now) {
  double sumt =
      now.a + now.b + now.c + (now.d + now.e) * now.m;
  return (now.s * now.f * now.m - now.p) / sumt;
}

#include<bits/stdc++.h>
using namespace std;
pair<int,int> pii;

int main() {
	int w,h,n;
	int xs,ys;
	int xg,yg;
	int c,d,x,y;
	int v[101][101];
	int u[101][101];
	int flag=0;
	int xx[4]={-1,0,1,0};
	int yy[4]={0,1,0,-1};
	int xxx,yyy;
while(cin>>w>>h,w||h){
	cin>>xs>>ys;
	cin>>xg>>yg;
	cin>>n;
	fill(v[0],v[101],0);
	fill(u[0],u[101],0);
	for (int i = 0; i < n; ++i) {
			cin>>c>>d>>x>>y;
			if(d==0){
				v[x][y]=c;	v[x+1][y]=c;	v[x+2][y]=c;	v[x+3][y]=c;
				v[x][y+1]=c;	v[x+1][y+1]=c;	v[x+2][y+1]=c;	v[x+3][y+1]=c;
			}
			if(d==1){
				v[x][y]=c;	v[x][y+1]=c;	v[x][y+2]=c;	v[x][y+3]=c;
				v[x+1][y]=c;	v[x+1][y+1]=c;	v[x+1][y+2]=c;	v[x+1][y+3]=c;
			}
	}
	queue<pair<int,int> > q;
	u[xs][ys]=1;
	int color=v[xs][ys];
	q.push(make_pair(xs,ys));
	while(!q.empty()){
		pii=q.front();q.pop();
		if(pii.first==xg&&pii.second==yg){flag=1;break;}
		for (int i = 0; i < 4; ++i) {
			xxx=xx[i]+pii.first;
			yyy=yy[i]+pii.second;
			if(xxx>=1&&xxx<=w&&yyy>=1&&yyy<=h&&u[xxx][yyy]!=1&&color==v[xxx][yyy]){
				u[xxx][yyy]=1;
				q.push(make_pair(xxx,yyy));
			}
		}
	}
	if(flag){cout<<"OK"<<endl;}
	else{cout<<"NG"<<endl;}
	flag=0;
}
	return 0;
}


#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>
#include<vector>
#include<stack>
#include<cstdlib>
#include<queue>
#include<list>
using namespace std;

int main(){
    int n, m, b, j, ans=0;
    cin>>n;
    int a[n+1];
    for(int i=0; i<n; i++) cin>>a[i];
    cin>>m;
    for(int i=0; i<m; i++){
        cin>>b;
        a[n]=b;
        for( j=0; a[j]!=b; j++);
        if(j!=n)ans++;

    }
    cout<<ans<<endl;

}

#include <iostream>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <stack>
#include <list>
using namespace std;

int main(int argc, char *argv[])
{
  vector<int> S;
  int q = 0;
  int t = 0;
  int C = 0;
  int n = 0;
  int s = 0;

  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> s;
    S.push_back(s);
  }
  sort(S.begin(), S.end());

  cin >> q;
  for (int i = 0; i < q; i++) {
    cin >> s;
    int start = 0;
    int end = S.size();
    while (start < end) {
      // cout << start <<" "<< end << "\n";
      if (S[(int)((end + start)/2)] < s) {
	start = (int)((end+start)/2)+1;
      }else if(S[(int)((end + start)/2)] > s){
	end = (int)((end + start)/2);
      }
      else{
	C++;
	break;
      }
    }

  }
  cout << C << "\n";
  return 0;
}


#include "bits/stdc++.h"
using namespace std;
using ll = long long;
#define rep(i, begin, n) for (int i = begin; i < n; i++)
#define repe(i, begin, n) for (int i = begin; i <= n; i++)
#define repr(i, begin, n) for (int i = begin; i > begin - n; i--)
#define repre(i, begin, end) for (int i = begin; i >= end; i--)

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

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

const int inf = 1000000007;
const int MOD = 1000000007;
const long long INF = 1000000000000000007;

// -------------------------------------------------------

int A, B;

int main() {
  cin >> A >> B;

  int cnt_w = 1, cnt_b = 1;
  cout << 100 << " " << 100 << "\n";
  rep(h, 0, 50) {
    rep(w, 0, 100) {
      if (h % 2 == 0 && w % 2 == 0) {
        if (cnt_b < B) {
          cout << '#';
          ++cnt_b;
        } else {
          cout << ".";
        }
      } else {
        cout << ".";
      }
      if (w == 99) {
        cout << "\n";
      }
    }
  }

  rep(h, 50, 100) {
    rep(w, 0, 100) {
      if (h % 2 == 1 && w % 2 == 0) {
        if (cnt_w < A) {
          cout << '.';
          ++cnt_w;
        } else {
          cout << '#';
        }
      } else {
        cout << '#';
      }
      if (w == 99) {
        cout << "\n";
      }
    }
  }
}

#pragma region
#define _USE_MATH_DEFINES
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <iomanip>
#include <cstdint>
#include <bitset>

using namespace std;
typedef long long ll;
//#define rep(i, s, e) for (int(i) = (s); (i) < (e); ++(i))
#define rep(i, e) for (int(i) = 0; (i) < (e); ++(i))
#define rrep(i, s) for (int(i) = (s) - 1; (i) >= 0; --(i))
#define all(x) x.begin(),x.end()

#pragma region UnionFind
struct UnionFind
{
	vector<int> par;

	UnionFind(int n) : par(n, -1) {}
	void init(int n) { par.assign(n, -1); }

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

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

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

	int size(int x)
	{
		return -par[root(x)];
	}
};
#pragma endregion
#pragma region GCD
int gcd(int a, int b)
{
	if (a%b == 0)return b;
	return gcd(b, a%b);
}
#pragma endregion
#pragma region chmin
template<class T> inline bool chmin(T& a, T b)
{
	if (a > b)
	{
		a = b;
		return true;
	}
	return false;
}
#pragma endregion
#pragma region chmax
template<class T> inline bool chmax(T& a, T b)
{
	if (a < b)
	{
		a = b;
		return true;
	}
	return false;
}
#pragma endregion
#pragma endregion

int main()
{
	int a, b; cin >> a >> b;
	vector<string> res;
	rep(i, 50)
	{
		string s = "";
		rep(j, 100)s += '.';
		res.push_back(s);
	}
	rep(i, 50)
	{
		string s = "";
		rep(j, 100)s += '#';
		res.push_back(s);
	}
	int x = 0;
	int y = 0;
	--a, --b;
	while (b > 0)
	{
		if (y >= 100)
		{
			x += 2;
			y = 0;
		}
		res[x][y] = '#';
		y += 2;
		--b;
	}
	x = 51;
	y = 0;
	while (a > 0)
	{
		if (y >= 100)
		{
			x += 2;
			y = 0;
		}
		res[x][y] = '.';
		y += 2;
		--a;
	}
	cout << 100 << " " << 100 << endl;
	rep(i, 100)cout << res[i] << endl;
}


#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>
#include<cstring>
#include<climits>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define LL long long
//#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
//char buf[(1 << 21) + 1], *p1 = buf, *p2 = buf;
inline int read() {
	bool f=0;int x=0;char c=getchar();
	while(c<'0'||'9'<c){if(c==EOF)exit(0);if(c=='-')f=1;c=getchar();}
	while('0'<=c&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
	return !f?x:-x;
}
#define MAXN 2000
#define INF 0x3f3f3f3f
#define Mod (int)(1e9+7)
LL fac[MAXN*MAXN+5],inv[MAXN*MAXN+5];
LL Pow(LL x,LL y){
	LL ret=1;
	while(y){
		if(y&1) ret=ret*x%Mod;
		x=x*x%Mod,y>>=1;
	}
	return ret;
}
void Prepare(){
	fac[0]=1;
	for(int i=1;i<=MAXN*MAXN;i++)
		fac[i]=fac[i-1]*i%Mod;
	inv[MAXN*MAXN]=Pow(fac[MAXN*MAXN],Mod-2);
	for(int i=MAXN*MAXN-1;i>=0;i--)
		inv[i]=inv[i+1]*(i+1)%Mod;
	return ;
}
LL f[MAXN+5][MAXN+5];
LL C(int n,int m){
	if(n<m) return 0;
	return fac[n]*inv[m]%Mod*inv[n-m]%Mod;
}
int main(){
	Prepare();
	int n=read(),k=read();
	if(k==1)
		puts("1"),exit(0);
	f[0][0]=1;
	for(int i=1;i<=n;i++){
		f[i][0]=1;
		for(int j=1;j<=i;j++)
			f[i][j]=(f[i-1][j]+C(n-i+(n-(j-1))*(k-1)-1,k-2)*f[i][j-1]%Mod)%Mod;
	}
	printf("%lld\n",f[n][n]*fac[n]%Mod);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = (a), i##_end_ = (b); i <= i##_end_; ++i)
#define drep(i, a, b) for(int i = (a), i##_end_ = (b); i >= i##_end_; --i)
#define clar(a, b) memset((a), (b), sizeof(a))
#define debug(...) fprintf(stderr, __VA_ARGS__)
typedef long long LL;
typedef long double LD;
const int BUF_SIZE = (int)1e6 + 10;
struct fastIO {
	char buf[BUF_SIZE], buf1[BUF_SIZE];
	int cur, cur1; FILE *in, *out;
	fastIO() { cur = BUF_SIZE, in = stdin, out = stdout; cur1 = 0; }
	inline char getchar() { if(cur == BUF_SIZE) fread(buf, BUF_SIZE, 1, in), cur = 0; return *(buf + (cur++)); }
	inline void putchar(char ch) { *(buf1 + (cur1++)) = ch; if (cur1 == BUF_SIZE) fwrite(buf1, BUF_SIZE, 1, out), cur1 = 0; } inline int flush() { if (cur1 > 0) fwrite(buf1, cur1, 1, out); return cur1 = 0; }
}IO;
#define getchar IO.getchar
#define putchar IO.putchar
LL read() {
	char ch = getchar();
	LL x = 0, flag = 1;
	for (;!isdigit(ch); ch = getchar()) if (ch == '-') flag *= -1;
	for (;isdigit(ch); ch = getchar()) x = x * 10 + ch - 48;
	return x * flag;
}
void write(LL x) {
	if (x < 0) putchar('-'), x = -x;
	if (x >= 10) write(x / 10);
	putchar(x % 10 + 48);
}

const int Maxn = 4009, Mod = 1e9 + 7;
int n, k, fac[Maxn * Maxn / 4], invFac[Maxn * Maxn / 4];

LL fpm(LL base, LL tims) {
	LL r = 1;
	while (tims) {
		if (tims & 1) r = r * 1ll * base % Mod;
		base = base * 1ll * base % Mod;
		tims >>= 1;
	}
	return r;
}

void init() {
	n = read(), k = read();
	fac[0] = 1;
	rep (i, 1, n * k) fac[i] = fac[i - 1] * 1ll * i % Mod;
	invFac[n * k] = fpm(fac[n * k], Mod - 2);
	drep (i, n * k - 1, 0) invFac[i] = invFac[i + 1] * (i + 1ll) % Mod;
}

LL C(int n, int m) {
	if (n < m) return 0;
	return 1ll * fac[n] * invFac[m] % Mod * invFac[n - m] % Mod;
}

LL dp[Maxn][Maxn];
void solve() {
	if (k == 1) {
		puts("1");
		return ;
	}
	dp[0][0] = 1;
	rep (i, 0, n)
		rep (j, 0, i) {
			(dp[i + 1][j] += dp[i][j]) %= Mod;
			(dp[i][j + 1] += dp[i][j] * 1ll * C(n * k - i - j * (k - 1) - 1, k - 2) % Mod) %= Mod;
		}
	cout << 1ll * dp[n][n] * fac[n] % Mod << endl;
}

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

	init();
	solve();

#ifdef Qrsikno
	debug("\nRunning time: %.3lf(s)\n", clock() * 1.0 / CLOCKS_PER_SEC);
#endif
	return IO.flush();
}


#include <iostream>
using namespace std;

void MySwap(int &a, int &b){
  int tmp = a;
  a = b;
  b = tmp;
}

int partition(int *A, int p, int r){
  int x = A[r];
  int i = p - 1;
  for(int j = p; j < r; j++){
    if(A[j] <= x){
      MySwap(A[++i], A[j]);
    }
  }
  MySwap(A[++i], A[r]);
  return i;
}

int main(){
  int A[100000], n, place;
  cin >> n;
  for(int i = 0; i < n; i++) cin >> A[i];
  place = partition(A, 0, n-1);
  for(int i = 0; i < n; i++)
    cout << (i==place?"[":"") << A[i] << (i==place?"]":"") << (i==n-1?'\n':' ');
  return 0;
}

#include <iostream>
#include <utility>
static int isort(long *a, int n, int g) {
    int c = 0;
    for (int i = g; i < n; ++i) {
        long v = a[i];
        int j = i - g;
        for (; j >= 0 && a[j] > v; j -= g, ++c) {
            a[j + g] = a[j];
        }
        a[j + g] = v;
    }
    return c;
}
static int ssort(long *a, int n) {
    int c = 0, m = 1, g[100] = { 1 };
    for (int gm = 3 * g[0] + 1; gm < n; gm = 3 * g[++m - 1] + 1) {
        g[m] = gm;
    }
    std::cout << m << std::endl;
    for (int i = 0; i < m; ++i) {
        std::cout << ((i == 0) ? "" : " ") << g[m - i - 1];
        c += isort(a, n, g[m - i - 1]);
    }
    std::cout << std::endl;
    return c;
}
int main() {
    int n;
    long a[1000000];
    std::cin >> n;
    for (int i = 0; i < n; ++i) {
        std::cin >> a[i];
    }
    std::cout << ssort(a, n) << std::endl;
    for (int i = 0; i < n; ++i) {
        std::cout << a[i] << std::endl;
    }
}