#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

class triple {
public:
    int type;
    int height;
    int mass;
};

class rec {
public:
    int w;
    int cc;
    int odd;
};

bool cmp(const triple & a, const triple & b) {
    return a.height < b.height;
}

int main() {
    int n, x;
    cin >> n >> x;
    vector<triple> c;
    for (int i = 0; i < n; ++i) {
        triple a;
        cin >> a.type;
        cin >> a.height;
        cin >> a.mass;
        c.push_back(a);
    }

    bool flag = 1;
    vector< pair < pair< bool, int> , set <int> > > d;
    for (int i = 0; i < n; ++i) {
        if (c[i].height <= x) {
            pair < pair< bool, int> , set <int> > t = make_pair(make_pair(c[i].type, x), set<int>());
            t.first.first ^= 1;
            t.second.insert(i);
            t.first.second += c[i].mass;
            d.push_back(t);
            flag = 1;
        }
    }
    while (flag) {
        flag = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < d.size(); ++j) {
                if (d[j].first.first == c[i].type && d[j].second.find(i) == d[j].second.end() && d[j].first.second >= c[i].height) {
                    d[j].first.first ^= 1;
                    d[j].second.insert(i);
                    d[j].first.second += c[i].mass;
                    flag = 1;
                }
            }
        }
    }
    int max = 0;
    for (int i = 0; i < d.size(); ++i) {
        if (d[i].second.size() > max) {
            max = d[i].second.size();
        }
    }
    cout << max << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

class triple {
public:
    int type;
    int height;
    int mass = -1;
};

int main() {
    int n, x;
    cin >> n >> x;
    vector<triple> c;
    for (int i = 0; i < n; ++i) {
        triple a;
        cin >> a.type;
        cin >> a.height;
        cin >> a.mass;
        c.push_back(a);
    }
    int type = 0;
    int height = x;
    bool flag = 1;
    set<int> s;
    while (flag) {
        flag = 0;
        triple buf;
        int ind = -1;
        for (int i = 0; i < c.size(); ++i) {
            if (c[i].type == type && c[i].height <= height && s.find(i) == s.end() && buf.mass < c[i].mass) {
                 buf = c[i];
                 flag = 1;
                 ind = i;
            }
        }
        if (ind != -1) {
            height += buf.mass;
            type ^= 1;
            s.insert(ind);
        }
    }
    int max1 = s.size();
    type = 1;
    height = x;
    flag = 1;
    s.clear();
    while (flag) {
        flag = 0;
        triple buf;
        int ind = -1;
        for (int i = 0; i < c.size(); ++i) {
            if (c[i].type == type && c[i].height <= height && s.find(i) == s.end() && buf.mass < c[i].mass) {
                 buf = c[i];
                 flag = 1;
                 ind = i;
            }
        }
        if (ind != -1) {
            height += buf.mass;
            type ^= 1;
            s.insert(ind);
        }
    }
    cout << max(max1, (int)s.size()) << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

class triple {
public:
    int type;
    int height;
    int mass;
};

class rec {
public:
    int w;
    int cc;
    int odd;
};

int main() {
    int n, x;
    cin >> n >> x;
    vector<triple> c;
    for (int i = 0; i < n; ++i) {
        triple a;
        cin >> a.type;
        cin >> a.height;
        cin >> a.mass;
        c.push_back(a);
    }

    bool flag = 1;
    vector< pair < pair< bool, int> , set <int> > > d;
    for (int i = 0; i < n; ++i) {
        if (c[i].height <= x) {
            pair < pair< bool, int> , set <int> > t = make_pair(make_pair(c[i].type, x), set<int>());
            t.first.first ^= 1;
            t.second.insert(i);
            t.first.second += c[i].mass;
            d.push_back(t);
            flag = 1;
        }
    }
    while (flag) {
        flag = 0;
        for (int j = 0; j < d.size(); ++j) {
            vector< pair < pair< bool, int> , set <int> > > b;
            for (int i = 0; i < n; ++i) {
                if (d[j].first.first == c[i].type && d[j].second.find(i) == d[j].second.end() && d[j].first.second >= c[i].height) {
                    auto xb = d[j];
                    xb.first.first ^= 1;
                    xb.second.insert(i);
                    xb.first.second += c[i].mass;
                    b.push_back(xb);
                    flag = 1;
                }
            }
            if (!b.empty()) {
                d[j] = b.back();
                b.pop_back();
            }
            for (auto i : b) {
                d.push_back(i);
            }
        }
    }
    int max = 0;
    for (int i = 0; i < d.size(); ++i) {
        if (d[i].second.size() > max) {
            max = d[i].second.size();
        }
    }
    cout << max << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

class triple {
public:
    int type;
    int height;
    int mass;
};

class rec {
public:
    int w;
    int cc;
    int odd;
};

bool cmp(const triple & a, const triple & b) {
    return a.height < b.height;
}

int main() {
    int n, x;
    cin >> n >> x;
    vector<triple> c;
    for (int i = 0; i < n; ++i) {
        triple a;
        cin >> a.type;
        cin >> a.height;
        cin >> a.mass;
        c.push_back(a);
    }

    bool flag = 1;
    vector< pair < pair< bool, int> , set <int> > > d;
    for (int i = 0; i < n; ++i) {
        if (c[i].height <= 3) {
            pair < pair< bool, int> , set <int> > t = make_pair(make_pair(c[i].type, 3), set<int>());
            t.first.first ^= 1;
            t.second.insert(i);
            t.first.second += c[i].mass;
            d.push_back(t);
            flag = 1;
        }
    }
    while (flag) {
        flag = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < d.size(); ++j) {
                if (d[j].first.first == c[i].type && d[j].second.find(i) == d[j].second.end() && d[j].first.second >= c[i].height) {
                    d[j].first.first ^= 1;
                    d[j].second.insert(i);
                    d[j].first.second += c[i].mass;
                    flag = 1;
                }
            }
        }
    }
    int max = 0;
    for (int i = 0; i < d.size(); ++i) {
        if (d[i].second.size() > max) {
            max = d[i].second.size();
        }
    }
    cout << max << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

class triple {
public:
    int type;
    int height;
    int mass = -1;
};

int main() {
    int n, x;
    cin >> n >> x;
    vector<triple> c;
    for (int i = 0; i < n; ++i) {
        triple a;
        cin >> a.type;
        cin >> a.height;
        cin >> a.mass;
        c.push_back(a);
    }
    int type = 0;
    int height = x;
    bool flag = 1;
    set<int> s;
    while (flag) {
        flag = 0;
        triple buf;
        int ind = -1;
        for (int i = 0; i < c.size(); ++i) {
            if (c[i].type == type && c[i].height <= height && s.find(i) == s.end() && buf.mass < c[i].mass) {
                 buf = c[i];
                 flag = 1;
                 ind = i;
            }
        }
        if (ind != -1) {
            height += buf.mass;
            type ^= 1;
            s.insert(ind);
        }
    }
    int max1 = s.size();
    type = 1;
    height = x;
    flag = 1;
    s.clear();
    while (flag) {
        flag = 0;
        triple buf;
        int ind = -1;
        for (int i = 0; i < c.size(); ++i) {
            if (c[i].type == type && c[i].height <= height && s.find(i) == s.end() && buf.mass < c[i].mass) {
                 buf = c[i];
                 flag = 1;
                 ind = i;
            }
        }
        if (ind != -1) {
            height += buf.height;
            type ^= 1;
            s.insert(ind);
        }
    }
    cout << max(max1, (int)s.size()) << endl;
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
#include <cfloat>
#include <cstdio>

using namespace std;

typedef long long ll;

int a[2000], b[2000];

int main()
{
    int n, x;
    cin>>n>>x;
    for(int i=0; i<n; i++){
        int t, m, h;
        cin>>t>>h>>m;
        if(t) a[h-1]=max(a[h-1],m);
        else b[h-1]=max(b[h-1],m);
    }
    int count = 0;
    for(int i=0; i<2000; i++){
        if(x<i+1) break;
        if(a[i] && b[i]){
            count+=2;
            x+=a[i]+b[i];
        }
        else if(a[i]){
            count+=1;
            x+=a[i];
        }
        else if(b[i]){
            count+=1;
            x+=b[i];
        }
    }
    cout<<count<<endl;
    return 0;
}


#pragma comment(linker,"/STACK:256000000")

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <bitset>
#include <memory>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <string>
#include <cstring>
#include <fstream>
#include <functional>
#include <stack>
#include <complex>
#include <wchar.h>
#include <wctype.h>
#include <cmath>
#include <queue>
#include <ctime>
#include <numeric>

using namespace std;
const double PI = acos(-1.0);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef short int si;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<double,int> pdi;
typedef pair<int,double> pid;
#define sqr(x) ((x)*(x))
//#define prob
pii ma[2][2000],mat[2][2000];
int dp[2005];
const int INF=1e9;
int main()
{
#ifdef SNELTYN
puts("Task A:");
 freopen("test.in","r",stdin);
 //freopen("test.out","w",stdout);
#endif
#ifdef prob
 freopen(prob".in","r",stdin);
 //freopen(prob".out","w",stdout);
#endif
 int n,x,k=0,l=0;
 scanf("%d%d", &n, &x);
 for(int i=0; i<n; i++){
  int a,b,c;
  scanf("%d%d%d", &a, &b,&c);
  if(a==0){
   mat[0][k]=pii(b,c);
   ma[0][k++]=pii(b,c);
  }
  else{
   mat[1][l]=pii(b,c);
   ma[1][l++]=pii(b,c);
  }
 }

 int t=0,ans=0;
 k=0;
 dp[0]=x;
 for(int i=1; i<=n; i++){
  int mx=0,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=ma[t][j].first&&ma[t][j].second>mx)
    mx=ma[t][j].second, cnt=j;
  if(mx==0)
   break;
  ma[t][cnt].second=-INF;
  ma[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  k++;
  t^=1;
 }

 t=1, ans=k, k=0;
 for(int i=1; i<=n; i++){
  int mx=0,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=mat[t][j].first&&mat[t][j].second>mx)
    mx=mat[t][j].second, cnt=j;
  if(mx==0)
   break;
  mat[t][cnt].second=-INF;
  mat[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  k++;
  t^=1;
 }
 ans=max(ans,k);
 cout<<ans<<endl;
 return 0;
}


#pragma comment(linker,"/STACK:256000000")

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <bitset>
#include <memory>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <string>
#include <cstring>
#include <fstream>
#include <functional>
#include <stack>
#include <complex>
#include <wchar.h>
#include <wctype.h>
#include <cmath>
#include <queue>
#include <ctime>
#include <numeric>

using namespace std;
const double PI = acos(-1.0);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef short int si;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<double,int> pdi;
typedef pair<int,double> pid;
#define sqr(x) ((x)*(x))
//#define prob
pii ma[2][2000],mat[2][2000];
int dp[2000];
const int INF=1e9;
int main()
{
#ifdef SNELTYN
puts("Task A:");
 freopen("test.in","r",stdin);
 //freopen("test.out","w",stdout);
#endif
#ifdef prob
 freopen(prob".in","r",stdin);
 //freopen(prob".out","w",stdout);
#endif
 int n,x,k=0,l=0;
 scanf("%d%d", &n, &x);
 for(int i=0; i<n; i++){
  int a,b,c;
  scanf("%d%d%d", &a, &b,&c);
  if(a==0){
   mat[0][k]=pii(b,c);
   ma[0][k++]=pii(b,c);
  }
  else{
   mat[1][l]=pii(b,c);
   ma[1][l++]=pii(b,c);
  }
 }
 int t=0,mx=0;
 k=0;
 dp[0]=x;
 for(int i=1; i<=n; i++){
  int mx=-1,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=ma[t][j].first&&ma[t][j].second>mx)
    mx=ma[t][j].second, cnt=j;
  if(mx==0)
   break;
  ma[t][cnt].second=-INF;
  ma[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  t^=1;
 }

 for(int i=1; i<=n; i++)
  k+=dp[i]!=0;

 t=1;
 for(int i=1; i<=n; i++){
  int mx=-1,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=mat[t][j].first&&mat[t][j].second>mx)
    mx=mat[t][j].second, cnt=j;
  if(mx==0)
   break;
  mat[t][cnt].second=-INF;
  mat[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  t^=1;
 }
 int s=0;
 for(int i=1; i<=n; i++)
  s+=dp[i]!=0;
 cout<<max(k,s)<<endl;
 return 0;
}


#pragma comment(linker,"/STACK:256000000")

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <bitset>
#include <memory>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <string>
#include <cstring>
#include <fstream>
#include <functional>
#include <stack>
#include <complex>
#include <wchar.h>
#include <wctype.h>
#include <cmath>
#include <queue>
#include <ctime>
#include <numeric>

using namespace std;
const double PI = acos(-1.0);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef short int si;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<double,int> pdi;
typedef pair<int,double> pid;
#define sqr(x) ((x)*(x))
//#define prob
pii ma[2][2000],mat[2][2000];
int dp[2000];
const int INF=1e9;
int main()
{
#ifdef SNELTYN
puts("Task A:");
 freopen("test.in","r",stdin);
 //freopen("test.out","w",stdout);
#endif
#ifdef prob
 freopen(prob".in","r",stdin);
 //freopen(prob".out","w",stdout);
#endif
 int n,x,k=0,l=0;
 scanf("%d%d", &n, &x);
 for(int i=0; i<n; i++){
  int a,b,c;
  scanf("%d%d%d", &a, &b,&c);
  if(a==0){
   mat[0][k]=pii(b,c);
   ma[0][k++]=pii(b,c);
  }
  else{
   mat[1][l]=pii(b,c);
   ma[1][l++]=pii(b,c);
  }
 }
 int t=0,mx=0;
 k=0;
 dp[0]=x;
 for(int i=1; i<=n; i++){
  int mx=0,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=ma[t][j].first&&ma[t][j].second>mx)
    mx=ma[t][j].second, cnt=j;
  if(mx==0)
   break;
  ma[t][cnt].second=-INF;
  ma[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  t^=1;
 }

 for(int i=1; i<=n; i++)
  k+=dp[i]!=0;

 t=1;
 for(int i=1; i<=n; i++){
  int mx=0,cnt=0;
  for(int j=0; j<2000; j++)
   if(dp[i-1]>=mat[t][j].first&&mat[t][j].second>mx)
    mx=mat[t][j].second, cnt=j;
  if(mx==0)
   break;
  mat[t][cnt].second=-INF;
  mat[t][cnt].first=INF;
  dp[i]=dp[i-1]+mx;
  t^=1;
 }
 int s=0;
 for(int i=1; i<=n; i++)
  s+=dp[i]!=0;
 cout<<max(k,s)<<endl;
 return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
#include <cfloat>
#include <cstdio>

using namespace std;

typedef long long ll;

vector<pair<int, int> > a, b;

int comp(pair<int,int> a, pair<int,int> b){
    if(a.first<b.first) return 1;
    if(a.first>b.first) return 0;
    if(a.second>b.second) return 1;
    return 0;
}

int main()
{
    int n, x;
    cin>>n>>x;
    for(int i=0; i<n; i++){
        int t, m, h;
        cin>>t>>h>>m;
        if(t) a.push_back(make_pair(h, m));
        else b.push_back(make_pair(h, m));
    }

    sort(a.begin(), a.end(), comp);
    sort(b.begin(), b.end(), comp);

    int count1 = 0, count2 = 0;

    int c1=0, c2=0, cx=x;
    while(1){
        if(c1==a.size() || cx<a[c1].first) break;
        cx+=a[c1].second;
        c1++;
        count1++;
        if(c2==b.size() || cx<b[c2].first) break;
        cx+=b[c2].second;
        c2++;
        count1++;
    }
    c1=0, c2=0, cx=x;
    while(1){
        if(c1==b.size() || cx<b[c1].first) break;
        cx+=b[c1].second;
        c1++;
        count2++;
        if(c2==a.size() || cx<a[c2].first) break;
        cx+=a[c2].second;
        c2++;
        count2++;
    }
    cout<<max(count1,count2)<<endl;
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>

using namespace std;

typedef long long int64;

const int oo = 0x3f3f3f3f;

vector< pair<int, int> > A, B;
int X, Answer;
vector< vector<bool> > DP[2];

void Solve() {
    Answer = 0;
    int n = int(A.size()), m = int(B.size());
    DP[0] = DP[1] = vector< vector<bool> >(n + 1, vector<bool>(m + 1, false));
    DP[0][0][0] = DP[1][0][0] = true;
    for (int i = 0, sumA = 0; i <= n; ++i) {
        if (i > 0)
            sumA += A[i - 1].second;
        for (int j = 0, sumB = 0; j <= m; ++j) {
            if (j > 0)
                sumB += B[j - 1].second;
            if (i == 0 && j == 0)
                continue;
            if (i > 0 && DP[1][i - 1][j] && X + sumA + sumB - A[i - 1].second >= A[i - 1].first)
                DP[0][i][j] = true;
            if (j > 0 && DP[0][i][j - 1] && X + sumA + sumB - B[j - 1].second >= B[j - 1].first)
                DP[1][i][j] = true;
            if (DP[0][i][j] || DP[1][i][j])
                Answer = max(Answer, i + j);
        }
    }
}

void Read() {
    int n;
    cin >> n >> X;
    for (int i = 0; i < n; ++i) {
        int type, h, m;
        cin >> type >> h >> m;
        if (type == 0)
            A.push_back(make_pair(h, m));
        else
            B.push_back(make_pair(h, m));
    }
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
}

void Print() {
    cout << Answer << "\n";
}

int main() {
    #ifndef ONLINE_JUDGE
        assert(freopen("a.in", "r", stdin));
        assert(freopen("a.out", "w", stdout));
    #endif
    Read();
    Solve();
    Print();
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>

using namespace std;

typedef long long int64;

const int oo = 0x3f3f3f3f;

vector< pair<int, int> > A, B;
int X, Answer;
vector< vector<bool> > DP[2];

void Solve() {
    Answer = 0;
    int n = int(A.size()), m = int(B.size());
    /*DP[0] = DP[1] = vector< vector<bool> >(n + 1, vector<bool>(m + 1, false));
    DP[0][0][0] = DP[1][0][0] = true;
    for (int i = 0, sumA = 0; i <= n; ++i) {
        if (i > 0)
            sumA += A[i - 1].second;
        for (int j = 0, sumB = 0; j <= m; ++j) {
            if (j > 0)
                sumB += B[j - 1].second;
            if (i > 0 && DP[1][i - 1][j] && X + sumA + sumB - A[i - 1].second >= A[i - 1].first)
                DP[0][i][j] = true;
            if (j > 0 && DP[0][i][j - 1] && X + sumA + sumB - B[j - 1].second >= B[j - 1].first)
                DP[1][i][j] = true;
            if (DP[0][i][j] || DP[1][i][j])
                Answer = max(Answer, i + j);
        }
    }*/
    for (int i = 0, j = 0, side = 0, h = X; i < n && j < m; side ^= 1) {
        if (side == 0) {
            if (h >= A[i].first)
                h += A[i++].second;
            else
                break;
        } else {
            if (h >= B[j].first)
                h += B[j++].second;
            else
                break;
        }
        Answer = max(Answer, i + j);
    }
    for (int i = 0, j = 0, side = 1, h = X; i < n && j < m; side ^= 1) {
        if (side == 0) {
            if (h >= A[i].first)
                h += A[i++].second;
            else
                break;
        } else {
            if (h >= B[j].first)
                h += B[j++].second;
            else
                break;
        }
        Answer = max(Answer, i + j);
    }
}

void Read() {
    int n;
    cin >> n >> X;
    for (int i = 0; i < n; ++i) {
        int type, h, m;
        cin >> type >> h >> m;
        if (type == 0)
            A.push_back(make_pair(h, m));
        else
            B.push_back(make_pair(h, m));
    }
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
}

void Print() {
    cout << Answer << "\n";
}

int main() {
    #ifndef ONLINE_JUDGE
        assert(freopen("a.in", "r", stdin));
        assert(freopen("a.out", "w", stdout));
    #endif
    Read();
    Solve();
    Print();
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>

using namespace std;

typedef long long int64;

const int oo = 0x3f3f3f3f;

vector< pair<int, int> > A, B;
int X, Answer;
vector< vector<bool> > DP[2];

void Solve() {
    Answer = 0;
    int n = int(A.size()), m = int(B.size());
    /*DP[0] = DP[1] = vector< vector<bool> >(n + 1, vector<bool>(m + 1, false));
    DP[0][0][0] = DP[1][0][0] = true;
    for (int i = 0, sumA = 0; i <= n; ++i) {
        if (i > 0)
            sumA += A[i - 1].second;
        for (int j = 0, sumB = 0; j <= m; ++j) {
            if (j > 0)
                sumB += B[j - 1].second;
            if (i > 0 && DP[1][i - 1][j] && X + sumA + sumB - A[i - 1].second >= A[i - 1].first)
                DP[0][i][j] = true;
            if (j > 0 && DP[0][i][j - 1] && X + sumA + sumB - B[j - 1].second >= B[j - 1].first)
                DP[1][i][j] = true;
            if (DP[0][i][j] || DP[1][i][j])
                Answer = max(Answer, i + j);
        }
    }*/
    for (int i = 0, j = 0, side = 0, h = X; i <= n && j <= m; side ^= 1) {
        if (side == 0) {
            if (i < n && h >= A[i].first)
                h += A[i++].second;
            else
                break;
        } else {
            if (j < m && h >= B[j].first)
                h += B[j++].second;
            else
                break;
        }
        Answer = max(Answer, i + j);
    }
    for (int i = 0, j = 0, side = 1, h = X; i <= n && j <= m; side ^= 1) {
        if (side == 0) {
            if (i < n && h >= A[i].first)
                h += A[i++].second;
            else
                break;
        } else {
            if (j < m && h >= B[j].first)
                h += B[j++].second;
            else
                break;
        }
        Answer = max(Answer, i + j);
    }
}

void Read() {
    int n;
    cin >> n >> X;
    for (int i = 0; i < n; ++i) {
        int type, h, m;
        cin >> type >> h >> m;
        if (type == 0)
            A.push_back(make_pair(h, m));
        else
            B.push_back(make_pair(h, m));
    }
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
}

void Print() {
    cout << Answer << "\n";
}

int main() {
    #ifndef ONLINE_JUDGE
        assert(freopen("a.in", "r", stdin));
        assert(freopen("a.out", "w", stdout));
    #endif
    Read();
    Solve();
    Print();
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>

using namespace std;

typedef long long int64;

const int oo = 0x3f3f3f3f;

vector< pair<int, int> > A, B;
int X, Answer;

int Solve(const vector< pair<int, int> > &a, const vector< pair<int, int> > &b, int h) {
    int n = int(a.size()), m = int(b.size()), count = 0;
    vector<bool> usedA = vector<bool>(n, false), usedB = vector<bool>(m, false);
    for (int side = 0; ; side ^= 1) {
        if (side == 0) {
            int found = -1;
            for (int i = 0; i < n; ++i)
                if (!usedA[i] && a[i].first <= h && (found == -1 || a[i].second > a[found].second))
                    found = i;
            if (found == -1)
                return count;
            ++count;
            usedA[found] = true;
            h += a[found].second;
        } else {
            int found = -1;
            for (int i = 0; i < m; ++i)
                if (!usedB[i] && b[i].first <= h && (found == -1 || b[i].second > b[found].second))
                    found = i;
            if (found == -1)
                return count;
            ++count;
            usedB[found] = true;
            h += b[found].second;
        }
    }
    return 0;
}

void Solve() {
    Answer = max(Solve(A, B, X), Solve(B, A, X));
}

void Read() {
    int n;
    cin >> n >> X;
    for (int i = 0; i < n; ++i) {
        int type, h, m;
        cin >> type >> h >> m;
        if (type == 0)
            A.push_back(make_pair(h, m));
        else
            B.push_back(make_pair(h, m));
    }
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
}

void Print() {
    cout << Answer << "\n";
}

int main() {
    #ifndef ONLINE_JUDGE
        assert(freopen("a.in", "r", stdin));
        assert(freopen("a.out", "w", stdout));
    #endif
    Read();
    Solve();
    Print();
    return 0;
}


def read_next_line
  gets.chomp.split.map { |x| x.to_i }
end

n, k = read_next_line
a = read_next_line
g = []
for i in 0...a.size
  g << [a[i]]
end
if n > 1
  i, j = 0, 1
  for x in 1..k * n
    unless a.include? x
      g[i] << x
      j += 1
      if j == n
        j = 1
        i += 1
      end
    end
  end
end
g.each { |z| puts z * ' ' }


t = gets.split.collect{|x| x.to_i}
n,k = t[0], t[1]

a = gets.split.collect{|x| x.to_i}
answer = []

a.each do |c|
	print c,' '
	m = 1
	for i in 1..n*k
		if m == n
			break
		end
		if not a.include?(i) and not answer.include?(i)
			answer << i
			m+=1
			print i,' '
		end
	end
	puts
end


n,k = map(int,raw_input().split())

s = map(int,raw_input().split())
ls = []
for i in range(1,(n*k)+1):
    ls.append(i)
ps = [0]*((n*k)+1)

for i in range(k):
    ps[s[i]] = i+1

t = ((n*k)-k)/k
p = 1
count = 0
for i in range(1,(n*k)+1):
    if ps[i]==0:
        if count==t:
            p+=1
            ps[i]=p
            count+=1
        else:
            ps[i]=p
            count+=1

for i in range(1,k+1):
    for j in range(1,(n*k)+1):
        if ps[j]==i:
            print(j),
    print('')


n,k = map(int,raw_input().split())

s = map(int,raw_input().split())
ls = []
for i in range(1,(n*k)+1):
    ls.append(i)
ps = [0]*((n*k)+1)

for i in range(k):
    ps[s[i]] = i+1

t = ((n*k)-k)/k
p = 1
count = 0
for i in range(1,(n*k)+1):
    if ps[i]==0:
        if count==t:
            p+=1
            ps[i]=p
            count=0
            count+=1
        else:
            ps[i]=p
            count+=1

for i in range(1,k+1):
    for j in range(1,(n*k)+1):
        if ps[j]==i:
            print(j),
    print('')


# ~*~ coding:utf-8 ~*~

n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
o = range(1, k * n + 1)
c = [[] for i in xrange(k)]
for i, x in enumerate(a):
    c[i].append(x)
    o.remove(x)

for i in xrange(k):
    for j in xrange(n - 1):
        c[i].append(o.pop())

for p in c:
    print ' '.join(map(str, p))


n,k = [int(c) for c in raw_input().split()]
r = [int(c) for c in raw_input().split()]
s = set(xrange(1,n*k+1)) - set(r)
r2 = [[x] for x in r]
for i in xrange(1,n):
	for j in xrange(k):
		r2[j].append(s.pop())
print '\n'.join(' '.join(map(str,x)) for x in r2)


(n, k) = map(int, raw_input().split())
a = map(int, raw_input().split())
b = [False]*1000

for x in a:
    b[x]=True

for i in range(k):
    cnt = 1
    for j in range(1, 1000):

        if cnt == n:
            break
        if b[j]==False:
            print j,
            b[j]=True
            cnt += 1
    print a[i]


(n, k) = map(int, raw_input().split())
a = map(int, raw_input().split())
b = [False]*1000

for x in a:
    b[x]=True

for i in range(k):
    cnt = 1
    for j in range(1, 1000):
        if b[j]==False:
            print j,
            b[j]=True
            cnt += 1
            if cnt == n:
                break
    print a[i]


[n, k] = [int(x) for x in raw_input().split()]

a = [int(x) for x in raw_input().split()]

orange = range(1, n*k+1)

for ai in a:
    orange.remove(ai)

for i in range(k):
    print a[i],
    for o in orange[i*(n-1):(i+1)*(n-1)]:
        print o,
    print ''


R=lambda:map(int,raw_input().split())
n,k=R()
a=R()
b=filter(lambda x: x not in a, xrange(1,n*k+1))
for i in xrange(k):
  print ' '.join(map(str,[a[i]]+b[i*(n-1):(i+1)*(n-1)]))


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
p = range(1,n*k+1)
for x in xrange(k):
    ans = []
    ans.append(a[x])
    p.pop(p.index(a[x]))
    i = 0
    while len(ans) < n:
        if p[i] not in a:
            ans.append(p[i])
            del p[i]
        else:
            i += 1
    print " ".join(map(str,ans))


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
p = range(1,n*k+1)
for x in xrange(k):
    ans = []
    while len(ans) < n:
        if a[x] in p:
            ans.append(a[x])
            p.pop(p.index(a[x]))
        if p[-1] not in a:
            ans.append(p.pop())
    print " ".join(map(str,ans))


n,k=map(int,raw_input().split(' '))
a=[0]*999
b=map(int,raw_input().split(' '))
for i in b:
     a[i]=1
for bb in b:
     print bb,
     c=1
     for i in xrange(1,1000):
          if c==n:
               break
          if a[i]==0:
               print i,
               a[i]=1
               c+=1
     print


n,k=map(int,raw_input().split(' '))
a=[0]*999
b=map(int,raw_input().split(' '))
for i in b:
     a[i]=1
for bb in b:
     print bb,
     c=1
     for i in xrange(1,1000):
          if a[i]==0:
               print i,
               a[i]=1
               c+=1
               if c==n:
                    break
     print


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
m = range(1,n*k+1)
b = [0]*(k)
print b
for j in range(k):
    m.remove(a[j])

for j in range(k):
    b[j] = m[j*(n-1):(j*n+n-1)]

for i in range(k):
    print str(a[i]) + ' ' + ' '.join(str(h) for h in b[i])


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
m = range(1,n*k+1)
b = [0]*(k)
print m
for j in range(k):
    m.remove(a[j])
print m
for j in range(k):
    b[j] = m[j:j+n-1]
print b
for i in range(k):
    print str(a[i]) + ' ' + ' '.join(str(h) for h in b[i])


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
m = range(1,n*k+1)
b = [0]*(k)

for j in range(k):
    m.remove(a[j])
print m
for j in range(k):
    b[j] = m[j*n:j*n + n]
    print b[j]
for i in range(k):
    print str(a[i]) + ' ' + ' '.join(str(h) for h in b[i])


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
m = range(1,n*k+1)
b = [0]*(k)

for j in range(k):
    m.remove(a[j])

for j in range(k):
    b[j] = m[j*(n-1):(j*n+n-1)]

for i in range(k):
    print str(a[i]) + ' ' + ' '.join(str(h) for h in b[i])


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())
m = range(1,n*k+1)
b = [0]*(k)
for j in range(k):
    m.remove(a[j])
for j in range(k):
    b[j] = m[j*(n-1):j*(n-1)+n-1]
for i in range(k):
    print str(a[i]) + ' ' + ' '.join(str(h) for h in b[i])


n,k=map(int,raw_input().split())
l=map(int,raw_input().split())
occur=[i for i in xrange(1,n*k+1)]
for i in xrange(k):
    occur.remove(l[i])
for element in l:
    print element,
    for dummy in xrange(n-1):
         print occur.pop(),
    print


n, k = map(int, raw_input().split())
l = map(int, raw_input().split())
s = k-1
lf = []
for i in range(k):
    lf.append([])
    lf[i].append(l[i])
for i in range(1, (n*k)+1):
    if i not in l:
        lf[s].append(i)
        s = s - 1
    if (s == -1):
        s = k-1
for i in lf:
    for j in i:
        print j,
    print


if __name__ == '__main__':
	n, k = [int(_) for _ in raw_input().split()]
	a = [int(_) for _ in raw_input().split()]
	given = []
	orange = list(range(1, n * k + 1))
	for i in range(k):
		given.append([a[i]])
		orange.remove(a[i])
	for i in range(k):
		given[i].extend(orange[i * (n - 1):i * (n - 1) + n - 1])
	for i in range(k):
		print ' '.join([str(_) for _ in given[i]])


if __name__ == '__main__':
	n, k = [int(_) for _ in raw_input().split()]
	a = [int(_) for _ in raw_input().split()]
	given = []
	orange = list(range(1, n * k + 1))
	for i in range(k):
		given.append([a[i]])
		orange.remove(a[i])
	print(given)
	for i in range(k):
		given[i].extend(orange[i * (n - 1):i * (n - 1) + n - 1])
	for i in range(k):
		print ' '.join([str(_) for _ in given[i]])


#coding:utf-8
import sys
n, k = [int(x) for x in sys.stdin.readline().split()]
pref = [int(x) for x in sys.stdin.readline().split()]
spare = set(range(1,n*k+1)) - set(pref)
for i in range(k):
  print pref[i],
  for _ in range(n-1):
    print spare.pop(),
  print


def diff(first, second):
    second = set(second)
    return [item for item in first if item not in second]

n, k = [int(i) for i in raw_input().split()]
segments_wanted = [int(i) for i in raw_input().split()]

# each child gets exactly n orange segments
all_segments = [i for i in xrange(1, n*k + 1)]

unwanted = diff(all_segments, segments_wanted)

for seg in segments_wanted:
    res = [seg]
    count = n - 1
    for idx, i in enumerate(unwanted):
        if count <= 0:
            break
        if i == -1:
            continue

        res += [i]
        unwanted[idx] = -1
        count -= 1

    print ' '.join(map(str,res))


n, k = map(int, raw_input().split())
a = [[x] for x in map(int, raw_input().split())]
for i in [x for x in xrange(1, n * k + 1) if [x] not in a]:
    a[i % k].append(i)
for l in a: print ' '.join(map(str, l))


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i : i + n]
b = chunks([x for x in xrange(1, n * k + 1) if x not in a], n - 1)
for p in ([x] + y for x, y in zip(a, b)):
    print ' '.join(map(str, p))


n, k = map(int, raw_input().split())
a = [[x] for x in map(int, raw_input().split())]
for i in [x for x in xrange(1, n * k + 1) if [x] not in a]:
    a[(i - 1) % k].append(i)
for l in a: print ' '.join(map(str, l))


n, k = map(int, raw_input().split())
a = [[x] for x in map(int, raw_input().split())]
b = [x for x in xrange(1, n * k + 1) if [x] not in a]
for i in xrange(len(b)):
    a[i % k].append(b[i])
for l in a: print ' '.join(map(str, l))


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Test {
	public static void redirectIn(String fileName){
		FileInputStream fileStream=null;
		try {
			fileStream=new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BufferedInputStream input=new BufferedInputStream(fileStream);
		System.setIn(input);
	}
	public static void redirectOut(String fileName){
		FileOutputStream fileStream=null;
		try {
			fileStream=new FileOutputStream(fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		PrintStream output=new PrintStream(fileStream);
		System.setOut(output);
	}
	public static Scanner initCin(){
		redirectIn("test.in");
		return new Scanner(new BufferedInputStream(System.in));
	}
	public static PrintStream initOut(){
//		redirectOut("output.txt");
		return System.out;
	}

	public final static PrintStream out=initOut();
	public final static Scanner cin=initCin();

	public static void main(String[] args){
		Solution sol=new Solution();
		sol.run(out, cin);
	}
}

class Solution{
	int n,m;
	List<Integer>[] nodes;
	List<int[]>[] query;
	int[] ans,ID;
	HashMap<String, Integer> map=new HashMap<>();

	Set<Integer> merge(Set<Integer> a,Set<Integer> b){
		if(a.size()<b.size()){
			b.addAll(a);
			return b;
		}
		a.addAll(b);
		return b;
	}
	List<Set<Integer>> merge(List<Set<Integer>> a,List<Set<Integer>> b){
		if(a.size()<b.size()){
			return merge(b, a);
		}
		for(int i=a.size()-1,j=b.size()-1;i>=0&&j>=0;--i,--j){
			a.set(i, merge(a.get(i),b.get(j)));
		}
		return a;
	}
	List<Set<Integer>> dfs(int u,int depth){
		List<Set<Integer>> dp=new ArrayList<>();
		for(int i:nodes[u]){
			dp=merge(dp, dfs(i, depth+1));
		}
		Set<Integer> temp=new TreeSet<Integer>();
		temp.add(ID[u]);
		dp.add(temp);
		 for(int[] i:query[u]){
			 if(i[0]<dp.size()){
				 ans[i[1]]=dp.get(dp.size()-1-i[0]).size();
			 }
		 }
		 return dp;
	}
	@SuppressWarnings("unchecked")
	void run(PrintStream out,Scanner cin){
		n=cin.nextInt();
		ID=new int[n+1];
		nodes=new List[n+1];
		query=new List[n+1];
		for(int i=0;i<n+1;++i){
			nodes[i]=new ArrayList<Integer>();
			query[i]=new ArrayList<int[]>();
		}
		for(int i=1;i<=n;++i){
			String name=cin.next();
			if(!map.containsKey(name)){
				map.put(name, i);
			}
			ID[i]=map.get(name);
			nodes[cin.nextInt()].add(i);
		}
		m=cin.nextInt();
		ans=new int[m];
		for(int i=0;i<m;++i){
			int v=cin.nextInt(),k=cin.nextInt();
			query[v].add(new int[]{k,i});
		}
		dfs(0, 0);
		for(int i:ans) out.println(i);
	}
}


import sys
def RedirectIO():
    sys.stdin=open("test.in","r")
#    sys.stdout=open("output.txt","w")
#RedirectIO()
def main():
    n,k=map(int,raw_input().split())
    a=map(lambda x:int(x)-1,raw_input().split())
    vis=[False]*n*k
    for i in a:
        vis[i]=True
    cur=0
    for i in xrange(k):
        num=0
        print a[i],
        while num<n-1:
            if vis[cur]==False:
                print cur+1,
                num+=1
            cur+=1
main()


import sys
def RedirectIO():
    sys.stdin=open("test.in","r")
#    sys.stdout=open("output.txt","w")
#RedirectIO()
def main():
    n,k=map(int,raw_input().split())
    a=map(lambda x:int(x)-1,raw_input().split())
    vis=[False]*n*k
    for i in a:
        vis[i]=True
    cur=0
    for i in xrange(k):
        num=0
        print a[i]+1,
        while num<n-1:
            if vis[cur]==False:
                print cur+1,
                num+=1
            cur+=1
main()


n, k = [int(x) for x in raw_input().split()]
U = [False]*(n*k)
A = [int(x)-1 for x in raw_input().split()]
for x in A:
    U[x] = True
for i in range(k):
    j = 0
    for x in range(n*k):
        if not U[x]:
            U[x] = True
            print x+1,
            j += 1
            if j == n-1:
                break
    print A[i]+1


s1 = raw_input()
s2 = raw_input()

l1 = s1.strip.split()
l2 = s2.strip.split()

n = int(l1[0])
k = int(l2[1])

d = {}
for i in l2:
    d[int(i)] = 1

c = 0
p = 0
s = ''
for i in range(1,(2+n*k)):
    if c == n:
        print(s)
        c = 0
        p = 0
        s = ''
    else:
        try:
            if d[i] == 1:
                if p == 0:
                    s = s + str(i)+' '
                    c = c + 1
                    p = 1
        except KeyError:
            s = s + str(i) + ' '
            c = c + 1


s1 = raw_input()
s2 = raw_input()

l1 = s1.strip.split()
l2 = s2.strip.split()

n = int(l1[0])
k = int(l2[1])

d = {}
for i in l2:
    d[int(i)] = 1

c = 0
p = 0
s = ''
for i in range(1,(1+n*k)):
    if c == n:
        print(s)
        c = 0
        p = 0
        s = ''
    else:
        try:
            if d[i] == 1:
                if p == 0:
                    s = s + str(i)+' '
                    c = c + 1
                    p = 1
        except KeyError:
            s = s + str(i) + ' '
            c = c + 1


s1 = raw_input()
s2 = raw_input()

l1 = s1.strip.split()
l2 = s2.strip.split()

n = int(l1[0])
k = int(l2[1])

d = {}
for i in l2:
    d[int(i)] = 1

c = 0
p = 0
s = ''
for i in range(1,(1+n*k)):
    if c == n:
        print(s)
        c = 0
        p = p + 1
        s = ''
    else:
        try:
            if i == p:
                s = s + str(i)+' '
                d[i] = 0
                c = c + 1
        except KeyError:
            s = s + str(i) + ' '
            c = c + 1


s1 = raw_input()
s2 = raw_input()

l1 = s1.strip().split()
l2 = s2.strip().split()

n = int(l1[0])
k = int(l1[1])

d = {}
for i in l2:
    d[int(i)] = 1

c = 0
p = 0
f = 0
s = ''
for i in range(1,(2+n*k)):
    if c == n:
        print(s)
        c = 0
        s = ''
        f = 0

    if f == 0:
        try:
            s = s + l2[p]+' '
        except IndexError:
            y = 2

        f = 1
        p = p + 1
        c =c +1

    try:
        if d[i] == 1:
            ohu = 12
    except KeyError:
        s = s + str(i) + ' '
        c = c + 1
        continue


s1 = raw_input()
s2 = raw_input()

l1 = s1.strip().split()
l2 = s2.strip().split()

n = int(l1[0])
k = int(l1[1])

d = {}
for i in l2:
    d[int(i)] = 1

print(n,k)

c = 0
p = 0
f = 0
s = ''
for i in range(1,(2+n*k)):
    if c == n:
        print(s)
        c = 0
        s = ''
        f = 0
    if p == k:
        break
    if f == 0:
        s = s + l2[p]+' '
        f = 1
        p = p + 1
        c =c +1

    try:
        if d[i] == 1:
            ohu = 12
    except KeyError:
        s = s + str(i) + ' '
        c = c + 1
        continue


n,k=map(int,raw_input().split(' '))
a=map(int,raw_input().split(' '))
num=range(1,n*k+1)
res=[]
for i in range(k):
    res.append([a[i]])
    num.pop(a[i]-1)
for i in res:
    while len(i)<n:
        i.append(num.pop(0))
for i in res:
    for j in i:
        if j!=i[-1]:
            print j,
        else:
            print j


n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
num=range(1,n*k+1)
res=[]
for i in range(k):
    res.append([a[i]])
    num.remove(a[i])
for i in res:
    while len(i)<n:
        i.append(num.pop(0))
for i in res:
    for j in i:
        if j!=i[-1]:
            print j,
        else:
            print j


n,k=raw_input().split()
n=int(n)
k=int(k)
choice=[int(x) for x in raw_input().split()]
num=[]
#print choice
for i in range(1,(n*k)+1):
	num.append(i)
#print num
pri=[]
for i in choice:
	a=num.pop(num.index(i))
	pri.append([a])
#print pri
#print num
for i in range(len(pri)):
	for j in range((n)-1):
		pri[i].append(num[0])
		num.pop(0)
#print num
#print pri
for i in range(len(pri)):
	for j in pri[i]:
		print j,
	print


n, k = map(int, raw_input().strip().split())
num = [str(i) for i in range(1,n*k+1)]
num_children = [0]*k
arr = map(str, raw_input().strip().split())
for a0 in range(k):
	num.remove(arr[a0])

i = 0
j = 0
while i<n*k-k:
	#print i, i+n-1
	#print num[i:i+n-1]
	print ' '.join([arr[j]] + num[i:i+n-1])
	i+=n-1
	j+=1


n, k = map(int, raw_input().strip().split())
num = [str(i) for i in range(1,n*k+1)]
num_children = [0]*k
arr = map(str, raw_input().strip().split())
strings = ['']*k
for a0 in range(k):
	num.remove(arr[a0])
	strings[a0]+=arr[a0]+' '

i = 0
j = 0
while i<n*k-k:
	strings[j]+=' '.join(num[i:i+n-1])
	i+=n-1
	j+=1
i=0
while i<k:
	print strings[i]
	i+=1


(n, k) = map(int, raw_input().split())
a = map(int, raw_input().split())
lst = [ i + 1 for i in range(n * k) ]
for aa in a:
        lst.pop(lst.index(aa))
for aa in a:
        print aa,
        for i in range(n - 1):
                print lst.pop(),
        print


import sys
import copy
import os

def next(b, c, n):
	for i in range(c,n):
		if b[i] == 0:
			return i
	return -1

def main(cin):
	nv = map(int,cin.readline().strip().split())
	n = nv[0]
	k = nv[1]
	v = map(int, cin.readline().strip().split())
	b = [0 for i in range(k*n+1)]

	res = [[] for i in range(k)]

	for i in range(k):
		t = [str(v[i])]
		b[v[i]] = 1
		res[i] = t

	c = 1

	for i in range(k):
		for j in range(n-1):
			c = next(b,c,n*k+1)
			res[i].append(str(c))
			b[c] = 1

	for i in range(k):
		print ' '.join(res[i])

if __name__ == "__main__":
	cin = sys.stdin
	if (os.path.exists('best.txt')):
		cin = open('best.txt')
	main(cin)


#!/usr/bin
from sys import stdin
n, k = map(int, stdin.readline().split())
requests = map(int, stdin.readline().split())
lib = {}.fromkeys(requests)
nottaken = [ w+1 for w in xrange(n*k) if w+1 not in lib ]
for t in xrange(k):
    print requests[t],
    for d in xrange(n-1):
        print nottaken.pop(),


#!/usr/bin
from sys import stdin
n, k = map(int, stdin.readline().split())
requests = map(int, stdin.readline().split())
lib = {}.fromkeys(requests)
nottaken = [ w+1 for w in xrange(n*k) if w+1 not in lib ]
for t in xrange(k):
    print requests[t],
    for d in xrange(n-1):
        print nottaken.pop(),
    print


a = []
rst = []
n, k = map(int, raw_input().split(' '))
a = map(int, raw_input().split(' '))
al = range(1, n*k+1)
pt = 0
for i in range(k):
	rst.append(a[i])
	j = 1
	while j < n:
		if al[pt] not in a:
			rst.append(al[pt])
			j += 1
		pt += 1
	print " ".join(map(str,rst))
	rst = []


a = []
rst = []
n, k = map(int, raw_input().split(' '))
a = map(int, raw_input().split(' '))
al = range(1, n*k+1)
pt = 0
for i in range(k):
	rst.append(a[i]);
	for j in range(n):
		if al[pt] not in a:
			rst.append(al[pt])
		pt += 1
	print " ".join(map(str,rst))
	rst = []


from sys import stdin, stdout

(n, k) = [int(val) for val in stdin.readline().strip().split()]

a = [int(val) for val in stdin.readline().strip().split()]

b = [0 for i in range(0,n*k)]
for v in a:
    b[v-1] = 1

p = 0

for i in range(0,k):
    stdout.write(str(a[i]))
    for j in range(1,n):
        while b[p] == 1:
            p += 1
        b[p] = 1
        stdout.write(' '+str(p))
    print('')


from sys import stdin, stdout

(n, k) = [int(val) for val in stdin.readline().strip().split()]

a = [int(val) for val in stdin.readline().strip().split()]

b = [0 for i in range(0,n*k)]
for v in a:
    b[v-1] = 1

p = 0

for i in range(0,k):
    stdout.write(str(a[i]))
    for j in range(1,n):
        while b[p] == 1:
            p += 1
        b[p] = 1
        stdout.write(' '+str(p+1))
    print('')


def main():
	o = raw_input()
	s = o.split()
	n = int(s[0])
	k = int(s[1])
	lis = []
        li =[]
	l =[]
	l2 =[]
	count = 1
	zz = raw_input()
	lis = zz.split()
        for d in range(len(lis)):
		lis[d] = int(lis[d])
	for u in range(1,n*k+1):
		li.append(u)
	for c in range(k):
		l.append(lis[c])
		for j in li:
			if((j not in lis) and count<n and (j not in l2)):
				l.append(j)
                                l2.append(j)
				count+=1
		for q in range(len(l)):
			print l[q]
		count = 1
                l = []

if __name__=="__main__":
	main()


def main():
	o = raw_input()
	s = o.split()
	n = int(s[0])
	k = int(s[1])
	lis = []
        li =[]
	l =[]
	count = 1
	zz = raw_input()
	lis = zz.split()
        for d in range(len(lis)):
		lis[d] = int(lis[d])
	for u in range(1,n*k+1):
		li.append(u)
	for c in range(k):
		l.append(lis[c])
		for j in li:
			if((j not in lis) and count<n):
				l.append(j)
                                li.pop(li.index(j))
				count+=1
		for q in range(len(l)):
			print l[q]
		count = 1
                l = []

if __name__=="__main__":
	main()


def main():
	o = raw_input()
	s = o.split()
	n = int(s[0])
	k = int(s[1])
	lis = []
        li =[]
	l =[]
	l2 =[]
	count = 1
	zz = raw_input()
	lis = zz.split()
        for d in range(len(lis)):
		lis[d] = int(lis[d])
	for u in range(1,n*k+1):
		li.append(u)
	for c in range(k):
		l.append(lis[c])
		for j in li:
			if((j not in lis) and count<n and (j not in l2)):
				l.append(j)
                                l2.append(j)
				count+=1
				print "li is " ,li
                print l
#		for q in range(len(l)):
#			print l[q]
		count = 1
                l = []

if __name__=="__main__":
	main()


x = map(int, raw_input().split())
y = map(int, raw_input().split())
#print x, y
s = set(y)
i=0
while i<x[0]:
    print y[i],
    j=0
    k=1
    while j<x[1]-1:
        if k<=x[0]*x[1] and k not in s:
            print k,
            s.add(k)
            j += 1
        k += 1
    print
    i += 1


x = map(int, raw_input().split())
y = map(int, raw_input().split())
#print x, y
s = set(y)
i=0
while i<x[1]:
    print y[i],
    j=0
    k=1
    while j<x[0]-1:
        if k<=x[0]*x[1] and k not in s:
            print k,
            s.add(k)
            j += 1
        k += 1
    print
    i += 1


n,k = map(int,raw_input().split())
a   = map(int,raw_input().split())
b = []
c=1

for i in xrange(k):
    print a[i],
    j=2
    while j<n+1:
        if (c not in a) and (c not in b):
            print c,
            b.append(c)
            j+=1
        c+=1
    print


import sys,math

hulp=[int(x) for x in sys.stdin.readline().split()]

n,k=hulp[0],hulp[1]

sinaasappel=[0]*(n*k)

a=[int(x) for x in sys.stdin.readline().split()]

for x in a:
    sinaasappel[x-1]=1

teller=0
for i in range(k):
    print a[i],
    x=1
    while x<n:
        if sinaasappel[teller]==0:
            print teller+1,
            x+=1
            sinaasappel[teller]=1
        teller+=1
    print


n,k = [int(x) for x in raw_input().split()]
import sys
times = k
lis = [0]
tmp = [int(x) for x in raw_input().split()]
for i in range(1 , n*k + 1):
    if i not in tmp:
        lis.append(i)
v = 0
kid = 1
while times:
    m = 1
    xx = []
    xx.append(tmp[v])
    v += 1
    while m <= n-1:
        xx.append(lis[(n-1)*(kid-1)+m])
        m += 1
    kid += 1
    times -= 1
    sys.stdout.write(" ".join(str(x) for x in xx))
    print


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())

d = [x for x in xrange(1, n * k + 1) if x not in a]
l = [[x] for x in a]

for i in xrange(k):
    for j in xrange(n-1):
        l[i].append(d.pop())
    print ' '.join(map(str,l[i]))


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
from sets import * #Set
import calendar
import heapq
import math
import copy
import itertools
myread = lambda : map(int,raw_input().split())
def solver():
    n,k = myread()
    all_num = n * k
    num = myread()
    check = [12345678 for x in range(all_num)]
    for i in range(len(num)):
        x = num[i]
        check[x-1] = i
    #print check
    for i in range(n-1):
        for j in range(k):
            for myk in range(all_num):
                if check[myk] == 12345678:
                    check[myk] = j
                    break

    for i in range(k):
        for j in range(len(check)):
            if check[j] == i:
                print j+1,
        print

if __name__ == "__main__":
    solver()


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
l = list()
bottom = 1
for i in xrange(k):
    print a[i],
    count = 0
    for j in xrange(bottom, n * k + 1):
        if j not in a:
            print j,
            count += 1
        if count == n - 1:
            print
            bottom = j + 1
            break


r=lambda:map(int, raw_input().split())
n,k=r()
a=r()
e=set(a)
a=map(lambda x: [x], a)
for i in range(1,n*k+1):
    if i not in e:
        a[(i - 1)/ n].append(i)
print '\n'.join([' '.join(map(str, e)) for e in a])


r=lambda:map(int, raw_input().split())
n,k=r()
a=r()
e=set(a)
a=map(lambda x: [x], a)
j=0
for i in range(1,n*k+1):
    if i not in e:
        a[j/(n-1)].append(i)
        j+=1
print '\n'.join([' '.join(map(str, e)) for e in a])


from collections import defaultdict
n,k = map(int,raw_input().strip().split())
arr = map(int,raw_input().strip().split())
d = defaultdict(list)
done = defaultdict(bool)
for i in range(k):
    d[i+1].append(arr[i])
    done[arr[i]]=True
at = 1
num = 1
while at<=(n*k):
    while len(d[num])<n:
        if not done[at]:
            d[num].append(at)
        at+=1
    num+=1
for i in range(k):
    print " ".join(map(str,d[i+1]))


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
print '\n'.join(' '.join(map(str, list(set(range(1, n * k + 1)) - set(a))[i * (n - 1) : (i + 1) * (n - 1)] + [a[i]])) for i in range(k))


####################################################
# -*- coding: utf-8 -*-
import sys

w = sys.stdout.write
read = sys.stdin.readline
reads = sys.stdin.read

def r(f=None):
    if f:
        return map(f, read().split())
    else:
        return read().split()

def rs(t,f=None):
    result = []
    result_append = result.append
    for i in xrange(t):
        if f:
            result_append(map(f, read().split()))
        else:
            result_append(list(read().split()))
    return result

####################################################
import math
sqrt = math.sqrt
from collections import deque

n, k = r(int)
ax = r(int)

i = 1
j = 1
while i <= k:
    w("%s " % ax[i-1])
    h = 1
    while h < n:
        if j not in ax:
            w("%s " % j)
            h += 1
        j += 1
    w("\n")
    i += 1


#!/usr/bin/python
n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
ans = range(1, n*k+1)
foo = []
for i in range(len(a)):
    ans.remove(a[i])

A = [[x] for x in a]

for j in range(k):
    for h in range(n-1):
        A[j].append(ans.pop())
    print ' '.join(map(str,A[j]))


n, k = map(int, raw_input().split())
req = map(int, raw_input().split())
ans = []
segments = [i+1 for i in range(n*k)]
for i in range(k):
    ans.append([])
    ans[i].append(req[i])
    segments.remove(req[i])
index = 0
i = 0
while(i<len(segments)):
    if (index == k):
        print index
        break
    if (len(ans[index]) != n):
        ans[index].append(segments[i])
        i+=1
    else:
        index += 1
for i in range(len(ans)):
    for j in range(len(ans[i])):
        print ans[i][j],
    print ""


n, k = map(int, raw_input().split())
a =  map(int, raw_input().split())

p = [i for i in xrange(1, n*k+1)]

r = []
for _ in xrange(k):
    ai = a.pop(0)
    p.remove(ai)
    t = [str(ai)]
    for _ in xrange(n-1):
        pi = p.pop()
        if pi not in a:
            t.append(str(pi))
        else:
            p.append(pi)
    r.append(' '.join(t))
print ' '.join(r)


n, k = map(int, raw_input().split())
a =  map(int, raw_input().split())

p = [i for i in xrange(1, n*k+1)]

r = []
for _ in xrange(k):
    ai = a.pop(0)
    p.remove(ai)
    t = [str(ai)]
    for _ in xrange(n-1):
        pi = p.pop(0)
        if pi not in a:
            t.append(str(pi))
        else:
            p.append(pi)
    r.append(' '.join(t))
print ' '.join(r)


n, k = map(int, raw_input().split())
a =  map(int, raw_input().split())

p = [i for i in xrange(1, n*k+1)]

r = []
for _ in xrange(k):
    ai = a.pop(0)
    p.remove(ai)
    t = [str(ai)]
    while len(t) < n:
        pi = p.pop(0)
        if pi not in a:
            t.append(str(pi))
        else:
            p.append(pi)
    r.append(' '.join(t))
print ' '.join(r)


n,k = list(map(int,raw_input().split()))
a = list(map(int,raw_input().split()))
apelsin = []
for i in xrange(1,n * k + 1):
	if i not in a:
		apelsin.append(i)
for i in xrange(k):
	print str(a[i]) + ' ' + ' '.join(map(str,apelsin[i * (n - 1):(i + 1) * (n - 1)]))


import sys

def readints() :
    l = sys.stdin.readline()
    return map(int, l.split(' '))

def readstring() :
    l = sys.stdin.readline()[:-1]
    return l

def readint() :
    l = sys.stdin.readline()
    return int(l)

def clearchars(s, chars) :
    for c in chars :
        s = s.replace(c, '')
    return s

def gcd(a, b) :
    if (a < b ) :
        a, b = b, a
    if b == 0 :
        return a
    return gcd(b, a % b)

def hist(a) :
    h = {}
    for x in a :
        try :
            h[x] += 1
        except KeyError :
            h[x] = 1
    return h

def lucky(n) :
    s = set(str(n))
    return all(map(lambda x: x in '47', s))

def yslice(a, j) :
    return map(lambda x: x[j], a)

def dist2(a, b) :
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

def chain_len(a) :
    l = .0
    for d, e in zip(a, a[1:]) :
        l += dist2(d, e)
    return l

def is_prime(x) :
    sq = int(x ** 0.5)
    for i in range(2, sq + 1) :
        if x % i == 0 :
            return False
    return True

digits = '0123456789'

def noe() :
    print "NO"
    exit(0)

def yese() :
    print "YES"
    exit(0)

n, k = readints()
a = readints()

x = list(set(range(1, n * k + 1)) - set(a))
for i in range(k) :
    print a[i],
    for j in range(i * (n - 1), (i + 1) * (n - 1)) :
        print x[j],
    print


#!/usr/bin/env python
# -*- coding: utf-8 -*-

def divide_orange ():
  # n*k - ����� ����������
  # k - ���������
  #
  n, k = map ( int, raw_input ().split () )
  if n < 1 or k < 1 or k > 30: return -1;

  a = map ( int, raw_input ().split () )

  ind = [ str(z) for z in xrange (1,n*k+1) if (z not in a) ]

  n_k = [ [ str(a_i) ] for a_i in a ]
  z = 0
  for i in xrange (k):
    n_k[i] += ind[z:z+n-1]
    z += n-1

  print "\n".join([ " ".join(n_k_i) for n_k_i in n_k ] )

divide_orange ()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

def divide_orange ():
  # n*k - ����� ����������
  # k - ���������
  #
  n, k = map ( int, raw_input ().split () )
  if n < 1 or k < 1 or k > 30: return -1;

  a = map ( int, raw_input ().split () )

  ind = [ str(z) for z in xrange (1,n*k+1) if (z not in a) ]

  n_k = [ [ str(a_i) ] for a_i in a ]
  for i in xrange (k):
    n_k[i] += ind[i:i+(n-1)]

  print "\n".join([ " ".join(n_k_i) for n_k_i in n_k ] )

divide_orange ()


n,k = map(int, raw_input().split())

y = 0
indices = []
for i in range(k):
     y = input()
     indices.append(y)
print indices

totalindices = range(1,n*k+1)
for j in range(k):
    segments = []
    segments.append(indices[j])
    for l in totalindices:
        if (len(segments) < n):
            if l not in indices and l in totalindices:
                segments.append(l)
                totalindices.remove(l)
    for m in range(n):
        print segments[m],
    print ("\n")


n,k = map(int, raw_input().split())

y = 0
indices = []
indices = map(int, raw_input().split())
print indices

totalindices = range(1,n*k+1)
for j in range(k):
    segments = []
    segments.append(indices[j])
    for l in totalindices:
        if (len(segments) < n):
            if l not in indices and l in totalindices:
                segments.append(l)
                totalindices.remove(l)
    for m in range(n):
        print segments[m],
    print ("\n")


n,k = map(int, raw_input().split())

y = 0
indices = []
indices = map(int, raw_input().split())
# print indices

totalindices = range(1,n*k+1)
for j in range(k):
    segments = []
    segments.append(indices[j])
    for l in totalindices:
        if (len(segments) < n):
            if l not in indices and l in totalindices:
                segments.append(l)
                totalindices.remove(l)
    for m in range(n):
        print segments[m],
    print ("\n")


n,k = map(int, raw_input().split())

y = 0
indices = []
indices = map(int, raw_input().split())
# print indices

totalindices = range(1,n*k+1)
for j in range(k):
    segments = []
    segments.append(indices[j])
    for l in totalindices:
        if (len(segments) < n):
            if l not in indices and l != 0:
                segments.append(l)
                totalindices[totalindices.index(l)] = 0
    for m in range(n):
        print segments[m],
    print


import sys

n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
index = 1
for i in range(k):
  ans = str(a[i])
  for j in range(n - 1):
    while index in a:
      index += 1
    ans += ' ' + str(index)
    index += 1
  print(ans)


import sys

n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
index = 1
for i in range(k):
  ans = [a[i]]
  for j in range(n - 1):
    while index in a:
      index += 1
    ans.append(index)
    index += 1
  print(ans)


import sys

n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
index = filter(lambda x: x not in a, range(1, n*k + 1))
for i in range(k):
  print ' '.join(map(str,[a[i]] + index[i*(n-1): (i+1)*(n-1)]))


n,k = map(int,raw_input().split())
s = map(int,raw_input().split())
s1 = set(s)
s2 = 1
for i in xrange(k):
    f = 0
    print s[i],
    while f<n-1:
        if s2 not in s1:
            print s2,
            f+=1
        s2+=1
    print


import sys
import math
import string
from collections import deque

# Function #
def read_int() :
    temp = raw_input().split();
    return map(int, temp);

def read_str() :
    temp = raw_input().split();
    return temp[0] if len(temp) == 1 else temp;

def write(output) :
    sys.stdout.write(output);

def writeln(output) :
    sys.stdout.write(str(output)+'\n');
# Class #

INF = 9123456789123456789
# Main Entry #

if __name__ == '__main__':
    n, k = read_int();
    want = read_int();
    childs = [];
    for ii in xrange(k) :
        childs.append([want[ii]]);

    want = set(want);

    for ii in xrange(k) :
        counter = 1;
        while (len(childs[ii]) != n) :
            if counter not in want :
                childs[ii].append(counter);
                want.add(counter);
            counter += 1;

    for ii in xrange(k) :
        strout = ""
        for jj in xrange(n) :
            strout += str(childs[ii][jj]) + " ";

        print strout;

    pass
# End Here #


##http://codeforces.ru/problemset/problem/244/A

n, k = map(int,raw_input().split())
likes = map(int,raw_input().split())

for i in xrange(1,n*k+1,1):
    if i not in likes:
        likes.append(i)

for i in xrange(k):
    for j in xrange(i, k*n, k):
        print likes[j],
    print ''


l1 = map(int, raw_input().split())
l2 = map(int, raw_input().split())
n = l1[0]
k = l1[1]

ans = [[] for i in range(k)]
i = 0
aux = [i+1 for i in range(n*k)]
i = 0
while i < k:
    ans[i] = ans[i] + [l2[i]]
    aux[l2[i]-1] = 0
    i = i + 1

i = 0
j = 0

while i < n*k:
    if aux[i] != 0:
        ans[j] = ans[j] + [aux[i]]
        aux[i] = 0
        if j == k - 1 :
            j = 0
        else:
            j = j + 1
    i = i + 1

def printArray(l):
    i = 0
    for i in l:
        print (i),
    print ""

i = 0
while i < len(ans):
    printArray(ans[i])
    i = i + 1


n, k = raw_input().split()
n = int(n)
k = int(k)
a = raw_input().split()
for i in xrange(0, k):
	 a[i] = int(a[i])

t = n * k
d = {}
booked = {}

for i in xrange(1, t+1):
	booked[i] = False
for i in xrange(1, k+1):
	d[i]  = [a[i - 1]]
	booked[a[i - 1]] = True
j = 1
for i in xrange(1, k+1):
	c = 0
	while (c < n - 1):
		if not (booked[j]):
			d[i].append(j)
			c += 1
		j += 1
for i in xrange(1, k+1):
	res = ""
	for x in d[i]:
		res += str(x) + " "
	print res


n,k=map(int,raw_input().split())
lst=map(int,raw_input().split())
a=[]
for i in range(1,n*k+1):
    a.append(i)

b=[]
for j in a:
    if not j in lst:
        b.append(j)
c=[]
for i in  range(k):
    c.append([lst[i]])

for i in range(k):
    c[i]+=b[i*(n-1):(i+1)*(n-1)]

for cc in c:
    cc=map(str,cc)
    print " ".join(cc)


n,k = map(int,raw_input().split())
ar = map(int,raw_input().split())
listofnot = [x for x in xrange(1,n*k+1) if x not in ar]
for x in ar:
	print x,
	for j in xrange(n-1):
		print listofnot[j],
	listofnot = listofnot[n-1:]


n,k = map(int,raw_input().split())
ar = map(int,raw_input().split())
listofnot = [x for x in xrange(1,n*k+1) if x not in ar]
for x in ar:
	print x,
	for x in xrange(k-1):
		print listofnot[x],
	listofnot = listofnot[k-1:]


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
res = []
t = 1
sa = set(a)
for i in range(k):
    r = [a[i]]
    for j in range(1, n):
        while t in sa: t += 1
        r.append(t)
        sa.add(t)
    res.append(r)
print '\n'.join([' '.join(map(str, r)) for r in res])


r=lambda:map(int,raw_input().split())
n,k=r()
s=r()
a=[x for x in range(1,n*k+1) if (x in s)==False]
n-=1
for i in range(k):
    print "%s" % " ".join(map(str,[s[i]]+a[i*n:i*n+n]))


n = int(input())
if n %2 == 1 :
	print(-1)
else:
	print (2,1,end = '')
	counter =3
	while counter < n :
		 print ('',counter+1,counter,end = '')
		 counter += 2


n = int(input())
if n == 1 :
	print(-1)
else:
	print (2,1,end = '')
	counter =3
	while counter < n :
		 print ('',counter+1,counter,end = '')
		 counter += 1


n = int(input())
if n %2 == 1 :
	print(-1)
else:
	print (2,1,end = '')
	counter =3
	while counter < n :
		 print ('',counter+1,counter,end = '')
		 counter += 1


n = int(input())
p = [i for i in range(n+1)]
if(n==1):
    print(-1)
else:
    for i in range(1,n+1):
        if(p[p[i]]==i):
            print(p[p[i]],end=' ')


n = int(input())
p = [i for i in range(n+1)]
if(n==1):
    print(-1)
else:
    for i in range(1,n+1,2):
        print(p[i+1],p[i],end=' ')


n = int(input())
p = [i for i in range(n+1)]
if(n%2==1):
    print(-1)
else:
    for i in range(1,n,2):
        print(p[i+1],p[i],end=' ')


n = int(input())
l = [0]*n
if(n%2!=0):
    print(-1)
else:
    for i in range(0,n-1,2):
        l[i]= (i+2)
        l[i+1] = (i+1)
s = ' '.join([str(elem) for elem in l])
print(s)


n = int(input())
l = [0]*n
if(n%2!=0):
    print(-1)
else:
    for i in range(0,n-1,2):
        l[i]= (i+2)
        l[i+1] = (i+1)
    s = ' '.join([str(elem) for elem in l])
    print(s)


n = int(input())

if n in [1, 3]:
    print(-1)
    exit()

print(*[i for i in range(n, 0, -1)])


n = int(input())

if n == 1:
    print(-1)
    exit()

if n == 3:
    print(3, 1, 2)
    exit()

print(*[i for i in range(n, 0, -1)])


n = int(input())

print(*[i for i in range(n, 0, -1)])


n = int(input())

if n % 2:
    print(-1)
    exit()

print(*[i for i in range(n, 0, -1)])


n = int(input())

if n == -1:
    print(-1)
    exit()

print(*[i for i in range(n, 0, -1)])


n = int(input())

if n == 1:
    print(-1)
    exit()

if n == 3:
    print(3, 1, 2)

print(*[i for i in range(n, 0, -1)])


n = int(input())

if n == 1:
    print(-1)
    exit()

print(*[i for i in range(n, 0, -1)])


n=int(input())
arr=[]
for i in range(n):
	arr.append(i+1)
if len(arr)==1:
	print(-1)
else:
	for i in range(n-1):
		print(arr[i+1],end=" ")
print(1)


n=int(input())
for i in range(n):
	if i+1==n:
		print(-1)
	else:
		while n>0:
			print(n)
			n=n-1


n=int(input())
arr=[]
for i in range(n):
	arr.append(i+1)
if (len(arr)%2)==1:
	print(-1)
else:
	for i in range(0,n-1,2):
		print(arr[i+1],arr[i],end=" ")


n=int(input())
arr=[]
for i in range(n):
	arr.append(i+1)
if len(arr)==1:
	print(-1)
else:
	for i in range(n-1):
		print(arr[i+1],end=" ")
    print(1)


n=int(input())
arr=[]
for i in range(n):
	arr.append(i+1)
if len(arr)==1:
	print(-1)
else:
	for i in range(n-1):
		print(arr[i+1],end=" ")
	print(1)


n= int(input())
if n%2 != 0 :
    print('-1')
else :
    for k in range(1,n//2+1):
        print(2*k,2*k-1,sep=' ',end=' ')


n = int(input())
if n%2 :
    print(-1)
else :
    print(*range(n,0,-1))


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
        print(*l,sep=' ')
    else:
        print("-1")


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
    #print(' '.join (d) for d in l)
        print(*l,sep=' ')
    else:
        print("-1")


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
        print(*l,sep=' ')
    #print(l)
    #print(' '.join (d) for d in l)
    else:
        print("-1")


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    while(i<len(l)):
        l[i],l[i+1]=l[i+1],l[i]
        i=i+2

    #print(' '.join (d) for d in l)
    print(*l,sep=' ')


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
    if(n%2!=0):
    	while(i<len(l)-1):
    		l[i],l[i+1]=l[i+1],l[i]
    		i+=1
    #print(l)
    #print(' '.join (d) for d in l)
    print(*l,sep=' ')


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
        print(" ".join(x) for x in l)
    else:
        print("-1")


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
    else:
        print("-1")
    #print(' '.join (d) for d in l)
    print(*l,sep=' ')


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    if(n%2==0):
    	while(i<len(l)):
        	l[i],l[i+1]=l[i+1],l[i]
        	i=i+2
        print(*l,sep=" ")
    else:
        print("-1")


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[(x+1) for x in range(n)]
    i=0
    while(i<len(l)):
        l[i],l[i+1]=l[i+1],l[i]
        i=i+2
    print(l)
    #print(' '.join (d) for d in l)
    print(*l,sep=' ')


n=int(input())
if(n<=1):
    print("-1")
else:
    l=[x for x in range(n)]
    i=0
    while(i<=len(l)):
        l[i],l[i+1]=l[i+1],l[i]
        i=i+2
    print(' '.join (l))


"""
instagram : essipoortahmasb2018
telegram channel : essi_python

"""
# ppi = i and pi ≠ i
n = int(input())
a = [0 for i in range(n+1)]

if n%2!=0:
    print(-1)
    exit()
# 1--->2
# 2--->1
# result if i choose p[i]==3 then i should choose p[3]=i
q = n
for i in range(1,n+1):
    if a[i]==0:
        a[i]=q
        a[q]=i
        q-=1
print(*a[1:])


"""
instagram : essipoortahmasb2018
telegram channel : essi_python

"""

n = int(input())
i=2;j=1
if n%2!=0:
    print(-1)
    exit()

for q in range(n//2-1):
    print(i,j,end=" ")
    i+=2
    j+=2

print(i,j)
# 1--->2
# 2--->1
# result if i choose p[i]==3 then i should choose p[3]=i


n=int(input())
if n%2!=0:
        print(-1)
else:
        for i in range(n,0,-1):
                print(i,end=" ")


a=int(input())
x=a
if a%2!=0:
  print("-1")
elif a%2==0:
  for i in range(a):
    a=x-i
    print(a)


a=int(input())
x=a
if a==1:
  print("-1")
elif a%2==0:
  for i in range(a):
    a=x-i
    print(a)
else:
  for i in range(a):
    a=x-i
    print(a)


n=int(input())
lst=list(range(1,n+1))
i=0
if n!=1:
    while i<len(lst)-1:
        temp=str(lst[i])
        lst[i]=str(lst[i+1])
        lst[i+1]=temp
        i+=2
    print(" ".join(lst))
else:
    print('-1')


n=int(input())
lst=list(range(1,n+1))
i=0
if n%2==0:
    while i<len(lst)-1:
        temp=str(lst[i])
        lst[i]=str(lst[i+1])
        lst[i+1]=temp
        i+=2
    print(" ".join(lst))
else:
    print('-1')


n=int(input())
lst=list(range(1,n+1))
i=0
if n!=1:
    while i<len(lst)-1:
        temp=str(lst[i])
        lst[i]=str(lst[i+1])
        lst[i+1]=temp
        i+=1
    print(" ".join(lst))
else:
    print('-1')


n = int(input())

if n%2==1:
    print(-1)
else:
    print(*range(n,0,-1))


n = int(input())

if n%2==0:
    print(-1)
else:
    print(*range(n,0,-1))


n=int(input())
if(n%2!=0):
    print(-1)
else:
    L=[0]*n
    for i in range(n):
        L[i]=1+i+((-1)**i)
    print(L)


n=int(input())
if(n%2!=0):
    print(-1)
else:
    L=[0]*n
    for i in range(n):
        L[i]=1+i+((-1)**i)
    print(*L)


n = int(input())
d = [i for i in range(1,n+1)]
g =""
c=0
for i in range(n):
	for j in d:
		if j !=i+1:
			g+=str(j)+" "
			d.remove(j)
			c+=1
if c!=n:
	print('-1')
else:
	print(g)


n = int(input())
d = [i for i in range(1,n+1)]
g =""

for i in range(n):
	for j in d:
		if j !=i+1:
			g+=str(j)+" "
			d.remove(j)
if len(g)==0:
	print('-1')
else:
	print(g)


n = int(input())
d = [i for i in range(1,n+1)]
g =[]
for i in range(n):
	for j in d:
		if j !=i+1:
			g.append(j)
			d.remove(j)
print(g)


n = int(input())
g =""
if n%2!=0:
	print('-1')
else:
	a=[i for i in range(n,0,-1)]
	for i in a :
		g+=str(i)+" "

print(g)


n = int(input())
d = [i for i in range(1,n+1)]
g =[]

for i in range(n):
	for j in d:
		if j !=i+1:
			g.append(j)
			d.remove(j)
if len(g)==0:
	print('-1')
else:
	print(g)


n=int(input())
l=[i for i in range(1,n+1)]
if n<=1:
	print("-1")
if n>1:
	l.pop(0)
	l.append(1)
	print(l)


n=int(input())
l=[i for i in range(1,n+1)]
if n<=1:
	print("-1")
if n>1:
	l.pop(0)
	l.append(1)
	print(*l)


n=int(input())
l=[i for i in range(1,n+1)]
if n%2!=0:
	print("-1")
if n%2==0:
	for i in range(0,n,2):
		z=l[i]
		x=l[i+1]
		l[i]=x
		l[i+1]=z
	print(*l)


n=int(input())
if(n%2==1):
	print(-1)
else:
	arr=[]
	arr.append(2)
	for i in range(1,n):
		if(i%2==0):
			arr.append(i+2)
		else:
			arr.append(i)
	print(arr)


n=int(input())
if(n%2==1):
	print(-1)
else:
	arr=[]
	arr.append(2)
	for i in range(1,n):
		if(i%2==0):
			arr.append(i+2)
		else:
			arr.append(i)
	print(*arr)


n=int(input())
if(n==1):
    print(-1)
else:
    if(n%2==0):
        for i in range(n,0,-1):
            print(i,end=" ")
    else:
        print(n,end=" ")
        for i in range(1,n):
            print(i,end=" ")


import math
n=int(input())
if(n==1):
    print(-1)
else:
    p=[]
    for i in range(1,n+1):
        p.append(i)
    k=math.ceil(n/2)
    arr1=p[:k]
    arr2=p[k:]
    lar=[0]
    for i in arr2:
        lar.append(i)
    for i in arr1:
        lar.append(i)
    flag=0
    for i in range(1,n):
        if(lar[lar[i]]!=i):
            flag=1
    if(flag==1):
        print(-1)
    else:
        for i in range(1,n+1):
            print(lar[i],end=" ")


import math
n=int(input())
p=[]
for i in range(1,n+1):
    p.append(i)
k=math.ceil(n/2)
arr1=p[:k]
arr2=p[k:]
lar=[0]
for i in arr2:
    lar.append(i)
for i in arr1:
    lar.append(i)
flag=0
for i in range(1,n):
    if(lar[lar[i]]!=i):
        flag=1
if(flag==1):
    print(-1)
else:
    for i in range(1,n+1):
        print(lar[i],end=" ")


n=int(input())
l=[]
if(n==1 or n%2!=0):
    print(-1)
else:
    for i in range(1,n,2):
        print(i+1,end=' ')
        print(i,end=' ')


n=int(input())
if(n%2!=0):
    print(-1)
else:
    for i in range(2,n+1,2):
        print(i,i-1,end=' ')


from itertools import permutations
def solve(n):
	if(n%2 != 0):
		return -1
	a = []
	for i in range(1, n+1):
		a.append(i)
	for i in range(0, n, 2):
		a[i], a[i+1] = a[i+1], a[i]
	return a

n = int(input())
x = solve(n)
if(x == -1):
	print(x)
else:
	for i in x:
		print(i, end = " ")
'''
x = []
for i in range(1, n+1):
	x.append(i)
perms = permutations(x)
ans = []
for perm in perms:
	f = 1
	for x in range(len(perm)):
		if(perm[perm[x]-1] != x+1 or perm[x] == x+1):
			f = 0
			break
	if(f):
		ans = perm
		break
if(len(ans) == 0):
	print(-1)
else:
	for i in ans:
		print(i, end = " ")
'''


from itertools import permutations

n = int(input())
x = []
for i in range(1, n+1):
	x.append(i)
perms = permutations(x)

ans = []
for perm in perms:
	f = 1
	for x in range(len(perm)):
		if(perm[perm[x]-1] != x+1):
			print(perm)
			f = 0
			break
	if(f):
		ans = perm
		break
if(len(ans) == 0):
	print(-1)
else:
	for i in ans:
		print(i, end = " ")


n=int(input())
ans=[]
if(n&1):
    print(-1)
else:
    for i in range(1,n+1,2):
        ans.append(i+1)
        ans.apped(i)
    print(*ans)


n=int(input())
ans=[]
if(n&1):
    print(-1)
else:
    for i in range(1,n+1,2):
        ans.append(i+1)
        ans.append(i)
    print(*ans)


n=int(input())
ans=[]
if(n&1):
    print(-1)
else:
    for i in range(1,n+1,2):
        ans.append(i+1)
        ans.apped(i)
print(*ans)


n=int(input())
a=1
if n==1:
	print('-1')
else:
	for i in range(n,0,-1):
		print(i,end=' ')


n=int(input())
a=1
if n==-1:
	print('-1')
for i in range(n,0,-1):
	print(i,end=' ')


n=int(input())
a=1
if n==1:
	print('-1')
for i in range(n,0,-1):
	print(i,end=' ')


n=int(input())
a=1
if n%2==1:
	print('-1')
else:
	for i in range(n,0,-1):
		print(i,end=' ')


n=int(input())
if n%2:
    print(-1)
else:
    print(*range(n,0,-1))


def printPermutation(n):

    # If n is odd
    if (n % 2 != 0):
        print(-1);

    # Otherwise
    else:
        for i in range(1, (n // 2) + 1):
            print((2 * i), (2 * i - 1), end = " ");

# Driver code
n = 4;
printPermutation(n);


n = int(input())
mas = []
if n % 2 == 1:
    print(-1)
    exit(0)
for i in range(1, n + 1):
    if i % 2 == 1:
        mas.append(str(i + 1))
    else:
        mas.append(str(i - 1))
print(' '.join(mas))


n = int(input())
mas = []
if n == 1:
    print(-1)
    exit(0)
for i in range(1, n + 1):
    if i % 2 == 1:
        mas.append(str(i + 1))
    else:
        mas.append(str(i - 1))
print(' '.join(mas))


n = int(input())
mas = []
for i in range(1, n + 1):
    if i % 2 == 1:
        mas.append(str(i + 1))
    else:
        mas.append(str(i - 1))
print(' '.join(mas))


size = int(input())
a = []
if(size%2 == 1):
    print("-1")
else:
    for i in range(1,size+1):
        a.append(i)
    for i in range(0,size,2):
        temp = a[i]
        a[i] = a[i+1]
        a[i+1] = temp
    for i in a:
        print(i, end=" ")


size = int(input())
a = []
for i in range(1,size+1):
    a.append(i)
for i in range(0,size,2):
    temp = a[i]
    a[i] = a[i+1]
    a[i+1] = temp
for i in a:
    print(i, end=" ")


size = int(input())
a = []
if(size == 1):
    print("-1")
else:
    for i in range(1,size+1):
        a.append(i)
    for i in range(0,size,2):
        temp = a[i]
        a[i] = a[i+1]
        a[i+1] = temp
    for i in a:
        print(i, end=" ")


n=int(input())
l=list()
if n%2==1:
    print(-1)
else:
    if n%2==0:
        for i in range(n,0,-1):
            print(i,end=" ")


n=int(input())
l=list()
if n==1:
    print(-1)
else:
    if n%2==0:
        for i in range(n,0,-1):
            print(i,end=" ")
    else:
        for i in range(n, 0, -1):
            l.append(i)
        l[0],l[len(l)//2]=l[len(l)//2],l[0]
        for i in l:
            print(i,end=" ")


n = int(input())
permutation = [0 for _ in range(n)]
if n == 1:
    print(-1)
else:
    for i in range(1, n+1):
        if i < n:
            permutation[i] = i
        else:
            permutation[0] = i
    for i in permutation:
        print(i, end=" ")


from random import shuffle

n = int(input())
if n == 1:
    print(-1)
else:
    permutation = [i for i in range(1, n+1)]
    shuffle(permutation)
    print(permutation)


n = int(input())
permutation = [0 for _ in range(n)]
if n == 1 or n % 2 != 0:
    print(-1)
else:
    for i in range(1, n+1):
        permutation[i-1] = i
    i = 1
    while i < n:
        permutation[i], permutation[i-1] = permutation[i-1], permutation[i]
        i += 2
    for i in permutation:
        print(i, end=" ")


n = int(input())
permutation = [0 for _ in range(n)]
if n == 1:
    print(-1)
else:
    for i in range(1, n+1):
        permutation[i-1] = i
    for i in permutation:
        print(i, end=" ")


n = int(input())
permutation = [0 for _ in range(n)]
if n == 1:
    print(-1)
else:
    for i in range(1, n+1):
        permutation[i-1] = i
    i = 1
    while i < n:
        if n % 2 == 0:
            permutation[i], permutation[i-1] = permutation[i-1], permutation[i]
            i += 2
        else:
            permutation[i-1], permutation[i] = permutation[i], permutation[i-1]
            i += 1
    for i in permutation:
        print(i, end=" ")


n = int(input())
permutation = [0 for _ in range(n)]
if n == 1:
    print(-1)
else:
    for i in range(1, n+1):
        permutation[i-1] = i
    i = 1
    while i < n:
        permutation[i], permutation[i-1] = permutation[i-1], permutation[i]
        i += 2
    for i in permutation:
        print(i, end=" ")


n = int(input())
if n & 1:
    print(-1)
else:
    k=2
    s=[0]*n
    for i in range(n):
        if not i & 1:
            s[i]=k
            k-=1
        else:
            s[i]=k
            k+=3
    print(s)


n = int(input())
if n & 1:
    print(-1)
else:
    k=2
    s=[0]*n
    for i in range(n):
        if not i & 1:
            s[i]=k
            k-=1
        else:
            s[i]=k
            k+=3
    print(*s)


n = int(input())

if n == 1:
    print(-1)

else:
    arr = [i for i in range(1,n+1)]

    if n&1 == 0:
        for i in range(0,n,2):
            arr[i], arr[i+1] = arr[i+1], arr[i]

    elif n > 1 and n&1 == 1:
        for i in range(0,n-1,2):
            arr[i], arr[i+1] = arr[i+1], arr[i]

    print(*arr)


n = int(input())

if n == 1:
    print(-1)

arr = [i for i in range(1,n+1)]

if n&1 == 0:
    for i in range(0,n,2):
        arr[i], arr[i+1] = arr[i+1], arr[i]

elif n > 1 and n&1 == 1:
    for i in range(0,n-1,2):
        arr[i], arr[i+1] = arr[i+1], arr[i]

print(arr)


n = int(input())

if n & 1== 1:
    print(-1)

else:
    arr = [i for i in range(1,n+1)]

    if n&1 == 0:
        for i in range(0,n,2):
            arr[i], arr[i+1] = arr[i+1], arr[i]

    print(*arr)


z=input;
n=int(z())
if n%2==1 or n==3:
    print(-1)
    exit()
else:
    l=[]
    for i in range(n,0,-1):
        l.append(i)
    print(*l)


z=input;
n=int(z())
if n==1 or n==3:
    print(-1)
    exit()
else:
    l=[]
    for i in range(n,0,-1):
        l.append(i)
    print(*l)


z=input;
n=int(z())
if n==1:
    print(-1)
    exit()
else:
    l=[]
    for i in range(n,0,-1):
        l.append(i)
    print(*l)


n = int(input(""))
t = True
i = n
while i > 2:
    if i//2 == 1:
        t = False
        break
    else:
        i /= 2
if t is True and n != 1:
    l = []
    for i in range(0, n, 2):
        l.append(str(i+2))
        l.append(str(i+1))
    print(" ".join(l))
else:
    print("-1")


n = int(input(""))
t = True
i = n
while i > 1:
    if i%2 == 1:
        t = False
        break
    else:
        i /= 2
if t is True and n != 1:
    l = []
    for i in range(0, n, 2):
        l.append(str(i+2))
        l.append(str(i+1))
    print(" ".join(l))
else:
    print("-1")


#!/usr/bin/env python3

if __name__ == "__main__":
	n = int(input())
	if n % 2 == 0:
		lst = list(str(x) for x in range(1, n+1))
		i = 0
		while i <= n-2:
			lst[i], lst[i+1] = lst[i+1], lst[i]
			i += 2
		print(" ".join(lst))
	else:
		print(-1)


#!/usr/bin/env python3

if __name__ == "__main__":
	n = int(input())
	if n != 1:
		lst = list(str(x) for x in range(1, n+1))
		i = 0
		while i < n-2:
			lst[i], lst[i+1] = lst[i+1], lst[i]
			i += 2
		print(" ".join(lst))
	else:
		print(-1)


#!/usr/bin/env python3

if __name__ == "__main__":
	n = int(input())
	if n != 1:
		lst = list(str(x) for x in range(2, n+1))
		lst.append(str(1))
		print(" ".join(lst))
	else:
		print(-1)


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 *
 * @author pttrung
 */
public class A_Round_302_Div1 {

	public static long MOD = 1000000007;
	static long[][] dp;
	static int[][] other;

	public static void main(String[] args) throws FileNotFoundException {
		// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
		// "output.txt")));
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();

		int n = in.nextInt();
		int m = in.nextInt();
		int b = in.nextInt();
		MOD = in.nextInt();
		int[] data = new int[n];

		for (int i = 0; i < n; i++) {
			data[i] = in.nextInt();
		}
		int[][] check = new int[m + 1][b + 1];
		int index = 0;

		LinkedList<Point> q = new LinkedList();
		dp = new long[m + 1][b + 1];
		dp[m][0] = 1;
		long[][] tmp;
		q.add(new Point(m, 0));
		long result = 0;
		for (int j = 0; j < n; j++) {
			index++;
			LinkedList<Point> nxt = new LinkedList();
			tmp = new long[m + 1][b + 1];
			while (!q.isEmpty()) {
				Point p = q.removeFirst();
				for (int k = 0; p.x - k >= 0 && k * data[j] + p.y <= b; k++) {
					if (p.x - k != 0) {
						tmp[p.x - k][k * data[j] + p.y] += dp[p.x][p.y];
						tmp[p.x -k ][k*data[j] + p.y] %= MOD;
					} else {
						result += dp[p.x][p.y];
						result %=MOD;
					}
					if (check[p.x - k][k * data[j] + p.y] != index
							&& p.x - k != 0) {
						check[p.x - k][k * data[j] + p.y] = index;
						nxt.add(new Point(p.x - k, k * data[j] + p.y));
					}
				}
			}

			q = nxt;
			dp = tmp;
		}

		for (int i = 0; i <= b; i++) {
			result += dp[0][i];
			result %= MOD;
		}
		out.println(result);

		out.close();
	}

	static int max(int index, int bug, int n, int[] data) {
		if (index == data.length) {
			return 0;
		}

		if (other[index][bug] != -1) {
			return other[index][bug];
		}
		int result = 0;
		for (int i = 0; i * data[index] <= bug && i <= n; i++) {
			result = Math.max(result,
					i + max(index + 1, bug - i * data[index], n, data));
		}
		return other[index][bug] = result;

	}

	public static int[] KMP(String val) {
		int i = 0;
		int j = -1;
		int[] result = new int[val.length() + 1];
		result[0] = -1;
		while (i < val.length()) {
			while (j >= 0 && val.charAt(j) != val.charAt(i)) {
				j = result[j];
			}
			j++;
			i++;
			result[i] = j;
		}
		return result;

	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	public static int digit(long n) {
		int result = 0;
		while (n > 0) {
			n /= 10;
			result++;
		}
		return result;
	}

	public static double dist(long a, long b, long x, long y) {
		double val = (b - a) * (b - a) + (x - y) * (x - y);
		val = Math.sqrt(val);
		double other = x * x + a * a;
		other = Math.sqrt(other);
		return val + other;

	}

	public static class Point implements Comparable<Point> {

		int x, y;

		public Point(int start, int end) {
			this.x = start;
			this.y = end;
		}

		@Override
		public int hashCode() {
			int hash = 5;
			hash = 47 * hash + this.x;
			hash = 47 * hash + this.y;
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			final Point other = (Point) obj;
			if (this.x != other.x) {
				return false;
			}
			if (this.y != other.y) {
				return false;
			}
			return true;
		}

		@Override
		public int compareTo(Point o) {
			return x - o.x;
		}
	}

	public static class FT {

		long[] data;

		FT(int n) {
			data = new long[n];
		}

		public void update(int index, long value) {
			while (index < data.length) {
				data[index] += value;
				index += (index & (-index));
			}
		}

		public long get(int index) {
			long result = 0;
			while (index > 0) {
				result += data[index];
				index -= (index & (-index));
			}
			return result;

		}
	}

	public static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	public static long pow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b == 1) {
			return a;
		}
		long val = pow(a, b / 2);
		if (b % 2 == 0) {
			return val * val % MOD;
		} else {
			return val * (val * a % MOD) % MOD;

		}
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("input.txt"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 *
 * @author pttrung
 */
public class A_Round_302_Div1 {

	public static long MOD = 1000000007;
	static long[][] dp;

	public static void main(String[] args) throws FileNotFoundException {
		// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
		// "output.txt")));
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		int n = in.nextInt();
		int m = in.nextInt();
		int b = in.nextInt();
		MOD = in.nextInt();
		int[] data = new int[n];
		for (int i = 0; i < n; i++) {
			data[i] = in.nextInt();
		}

		dp = new long[b + 1][m + 1];
		dp[b][m] = 1;
		Point[][] q = new Point[2][b * m + 1];
		int cur = 1;
		int[][] check = new int[b + 1][m + 1];
		int[][] v = new int[b + 1][m + 1];
		int[][] head = new int[2][2];
		head[0][1]++;
		q[0][0] = new Point(b, m);
		long[][] tmp = new long[b + 1][m + 1];
		for (int i = 0; i < n; i++) {

			head[cur][0] = 0;
			head[cur][1] = 0;
			while (head[1 - cur][0] < head[1 - cur][1]) {
				Point p = q[1 - cur][head[1 - cur][0]++];
				for (int j = 0; j <= p.y && j * data[i] <= p.x; j++) {
					if(v[p.x - (j * data[i])][p.y - j] != i + 1){
						v[p.x - (j * data[i])][p.y - j] = i + 1;
						tmp[p.x - (j * data[i])][p.y - j] = 0;
					}
					tmp[p.x - (j * data[i])][p.y - j] += dp[p.x][p.y];
					tmp[p.x - (j * data[i])][p.y - j] %= MOD;
					if (check[p.x - (j * data[i])][p.y - j] != i + 1) {
						check[p.x - (j * data[i])][p.y - j] = i + 1;
						q[cur][head[cur][1]++] = (new Point(
								p.x - (j * data[i]), p.y - j));
					}
				}
			}
			cur = 1 - cur;
			dp = tmp;

		}
		long result = 0;
		for (int i = 0; i <= b; i++) {

			result += dp[i][0];
			result %= MOD;
		}
		out.println(result);

		out.close();
	}

	public static int[] KMP(String val) {
		int i = 0;
		int j = -1;
		int[] result = new int[val.length() + 1];
		result[0] = -1;
		while (i < val.length()) {
			while (j >= 0 && val.charAt(j) != val.charAt(i)) {
				j = result[j];
			}
			j++;
			i++;
			result[i] = j;
		}
		return result;

	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	public static int digit(long n) {
		int result = 0;
		while (n > 0) {
			n /= 10;
			result++;
		}
		return result;
	}

	public static double dist(long a, long b, long x, long y) {
		double val = (b - a) * (b - a) + (x - y) * (x - y);
		val = Math.sqrt(val);
		double other = x * x + a * a;
		other = Math.sqrt(other);
		return val + other;

	}

	public static class Point implements Comparable<Point> {

		int x, y;

		public Point(int start, int end) {
			this.x = start;
			this.y = end;
		}

		@Override
		public int hashCode() {
			int hash = 5;
			hash = 47 * hash + this.x;
			hash = 47 * hash + this.y;
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			final Point other = (Point) obj;
			if (this.x != other.x) {
				return false;
			}
			if (this.y != other.y) {
				return false;
			}
			return true;
		}

		@Override
		public int compareTo(Point o) {
			return x - o.x;
		}
	}

	public static class FT {

		long[] data;

		FT(int n) {
			data = new long[n];
		}

		public void update(int index, long value) {
			while (index < data.length) {
				data[index] += value;
				index += (index & (-index));
			}
		}

		public long get(int index) {
			long result = 0;
			while (index > 0) {
				result += data[index];
				index -= (index & (-index));
			}
			return result;

		}
	}

	public static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	public static long pow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b == 1) {
			return a;
		}
		long val = pow(a, b / 2);
		if (b % 2 == 0) {
			return val * val % MOD;
		} else {
			return val * (val * a % MOD) % MOD;

		}
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("input.txt"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskA {

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int m = in.readInt();
        int b = in.readInt();
        int MOD = in.readInt();

        int[] a = new int[n + 1];

        for (int i = 1; i <= n; i++) a[i] = in.readInt();

        long[][][] dp = new long[2][m + 1][b + 1];
        dp[0][0][0] = 1;

        for (int idx = 1; idx <= n; idx++) {
            for (int lines = 0; lines <= m; lines++) {
                for (int bugs = 0; bugs <= b; bugs++) {

                    dp[idx & 1][lines][bugs] = dp[(idx - 1) & 1][lines][bugs] +
                            ((bugs >= a[idx]) && (lines > 0) ? dp[idx & 1][lines - 1][bugs - a[idx]] : 0);

                    if (dp[idx & 1][lines][bugs] >= MOD)   dp[idx & 1][lines][bugs] -= MOD;
                }
            }
        }

        long res = 0;
        for (int bugs = 0; bugs <= b; bugs++) {
            res += dp[n & 1][m][bugs];
            if (res >= MOD)  res -= MOD;
        }

        out.printLine(res);
    }
}

class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object...objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}