/*
Згадую теплий вечір, —
Це було, мов учора, —
Тримавши тебе за плечі,
В очах бачив синє море —
Бавився сяйвом місяць
В воді чистій і прозорій,
Й під хвиль колискову пісню
Чарівно ясніли зорі…

Нічого я більш не хочу,
Нічого мені не треба,
Тільки в рідні дивитись очі
І бачить безмежне небо,
Дні і весняні, й літні,
І восени, і взимку
За руки тримати рідні,
Відчути тепло й підтримку…

Тихо тобі шепочу
Шелестом світлого ранку,
Ніжно тебе лоскочу
Теплим дощем на світанку,
Дивлячись небом в очі,
Тільки сказати хочу —
Вип’ють самотні ночі
Душу твою до останку.
*/

//#pragma comment(linker, "/STACK:16777216")
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash

#define  INF 100000000
#define eps 1e-11
//#define M_PI 3.141592653589793
//#define mx 1000000000000ll
#define bs 1000000007
#define bsize 256

using namespace std;

 long n,ar[200000],s[200000],t,ans;
 long sq[200000];
 long q;

int main(){
//freopen("partition.in","r",stdin);
//freopen("partition.out","w",stdout);
//freopen("C:/input.txt","r",stdin);
//freopen("C:/output.txt","w",stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);

for (int i=0;i<=11000;i++)
sq[i]=i*i;

cin>>n;
for (int i=1;i<=n;i++)
cin>>ar[i];
for (int i=1;i<=n;i++)
{
 s[i]=s[i-1]+ar[i];
}

ans=1e9;

for (int l=1;l<=n;l++)
{
 for (int r=l+1;r<=n&&r<=l+10010;r++)
 {
  t=(r-l);
  q=abs(s[r]-s[l]);
  if (q<=10100){ans=min(ans,sq[q]+sq[t]);}
 }
}

cout<<ans<<endl;

cin.get();cin.get();
return 0;}


#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")
int main()
{
    long long ans=1000000000,x,n,a[100005],sq[100005],i,j,k,pre[100005]={0};
    scanf("%lld",&n);
    for(i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=a[i]+pre[i-1];

    }
    for(i=0;i<=100000;i++)
        sq[i]=i*i;
    for(i=1;i<=n;i++){
        for(j=i+1;j<=n;j++){
            if(sq[j-i]>ans)
                break;
            if(abs(pre[j]-pre[i])<100000&&sq[abs(pre[j]-pre[i])]<ans){
                x=sq[j-i]+sq[abs(pre[j]-pre[i])];

                if(x<ans)
                    ans=x;
            }
        }
    }
    printf("%lld",ans);
}


#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
using namespace std;
///#pragma GCC optimize("Ofast")
///#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("avx,avx2,fma")
long id1,id2,ans=1e9,x,n,a[100005],sq[100005],k,pre[100005];
int main()
{
    ios_base::sync_with_stdio(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        pre[i]=a[i]+pre[i-1];

    }
    for(int i=0;i<=11000;i++){
        sq[i]=i*i;

    }
    for(int i=1;i<=n;i++){
        for(int j=i+1;j<=n&&j<=i+10010;j++){
            id1=j-i;
            id2=abs(pre[j]-pre[i]);
            if(sq[id1]>ans)
                break;
            if(id2<10100){
                x=sq[id1]+sq[id2];

                if(x<ans)
                    ans=x;
            }
        }
    }
    cout<<ans;
}


#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")
int main()
{
    long long ans=1000000000,x,n,a[100005],sq[100005],i,j,k,pre[100005]={0};
    scanf("%lld",&n);
    for(i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=a[i]+pre[i-1];

    }
    for(i=0;i<=100000;i++)
        sq[i]=i*i;
    for(i=1;i<=n;i++){
        for(j=i+1;j<=n;j++){
            if(sq[j-i]>ans)
                break;
            if(abs(pre[j]-pre[i])<100000&&sq[pre[j]-pre[i]]<ans){
                x=sq[j-i]+sq[abs(pre[j]-pre[i])];

                if(x<ans)
                    ans=x;
            }
        }
    }
    printf("%lld",ans);
}


#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")

int main()
{
    long  ans=1000000000,x,n,a[100005],sq[100005],i,j,k,pre[100005]={0};
    scanf("%lld",&n);
    for(i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=a[i]+pre[i-1];

    }
    for(i=0;i<=100000;i++)
        sq[i]=i*i;
    for(i=1;i<=n;i++){
        for(j=i+1;j<=n;j++){
            if(sq[j-i]>ans)
                break;
            if(abs(pre[j]-pre[i])<100000&&sq[abs(pre[j]-pre[i])]<ans){
                x=sq[j-i]+sq[abs(pre[j]-pre[i])];

                if(x<ans)
                    ans=x;
            }
        }
    }
    printf("%lld",ans);
}


#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
using namespace std;
///#pragma GCC optimize("Ofast")
///#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("avx,avx2,fma")
long id1,id2,ans=1e9,x,n,a[100005],sq[100005],k,pre[100005];
int main()
{
    ios_base::sync_with_stdio(0)
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        pre[i]=a[i]+pre[i-1];

    }
    for(int i=0;i<=11000;i++){
        sq[i]=i*i;

    }
    for(int i=1;i<=n;i++){
        for(int j=i+1;j<=n&&j<=i+10010;j++){
            id1=j-i;
            id2=abs(pre[j]-pre[i]);
            if(sq[id1]>ans)
                break;
            if(id2<10100){
                x=sq[id1]+sq[id2];

                if(x<ans)
                    ans=x;
            }
        }
    }
    cout<<ans;
}


/*
Згадую теплий вечір, —
Це було, мов учора, —
Тримавши тебе за плечі,
В очах бачив синє море —
Бавився сяйвом місяць
В воді чистій і прозорій,
Й під хвиль колискову пісню
Чарівно ясніли зорі…

Нічого я більш не хочу,
Нічого мені не треба,
Тільки в рідні дивитись очі
І бачить безмежне небо,
Дні і весняні, й літні,
І восени, і взимку
За руки тримати рідні,
Відчути тепло й підтримку…

Тихо тобі шепочу
Шелестом світлого ранку,
Ніжно тебе лоскочу
Теплим дощем на світанку,
Дивлячись небом в очі,
Тільки сказати хочу —
Вип’ють самотні ночі
Душу твою до останку.
*/

//#pragma comment(linker, "/STACK:16777216")
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash

#define  INF 100000000
#define eps 1e-11
//#define M_PI 3.141592653589793
//#define mx 1000000000000ll
#define bs 1000000007
#define bsize 256

using namespace std;

 long n,ar[200000],s[200000],t,ans;
 long sq[200000];
 long q;

int main(){
//freopen("partition.in","r",stdin);
//freopen("partition.out","w",stdout);
//freopen("C:/input.txt","r",stdin);
//freopen("C:/output.txt","w",stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);

for (int i=0;i<=11000;i++)
sq[i]=i*i;

cin>>n;
for (int i=1;i<=n;i++)
cin>>ar[i];
for (int i=1;i<=n;i++)
{
 s[i]=s[i-1]+ar[i];
}

ans=1e9;

for (int l=1;l<=n;l++)
{
 for (int r=l+1;r<=n;r++)
 {
  t=(r-l);
  q=abs(s[r]-s[l]);
  if (q<=10100){ans=min(ans,sq[q]+sq[t]);}
 }
}

cout<<ans<<endl;

cin.get();cin.get();
return 0;}


#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
using namespace std;
///#pragma GCC optimize("Ofast")
///#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("avx,avx2,fma")

int main()
{
    long long ans=1000000000,x,n,a[100005],sq[100005],i,j,k,pre[100005]={0};
    scanf("%lld",&n);
    for(i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=a[i]+pre[i-1];

    }
    for(i=0;i<=11000;i++){
        sq[i]=i*i;

    }
    for(i=1;i<=n;i++){
        for(j=i+1;j<=n&&j<=i+11000;j++){
            if(sq[j-i]>ans)
                break;
            if(abs(pre[j]-pre[i])<11000){
                x=sq[j-i]+sq[abs(pre[j]-pre[i])];

                if(x<ans)
                    ans=x;
            }
        }
    }
    printf("%lld",ans);
}


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

int main()
{
    long long ans=1000000000,x,n,a[100005],i,j,k,pre[100005]={0};
    scanf("%lld",&n);
    for(i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=a[i]+pre[i-1];

    }
    for(i=1;i<=n;i++){
        for(j=i+1;j<=n;j++){

            x=(j-i)*(j-i)+(pre[j]-pre[i])*(pre[j]-pre[i]);

            if(x<ans)
                ans=x;
        }
    }
    printf("%lld",ans);
}


import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Arrays;
import java.awt.geom.Point2D;
import java.util.Vector;
import java.awt.Point;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Agostinho Junior (junior94)
 */
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);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
	OutputWriter out;

	final long INF = Long.MAX_VALUE;

	Comparator<Point> xComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.x - o2.x;
		}
	};
	Comparator<Point> yComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.y - o2.y;
		}
	};

    public void solve(int testNumber, InputReader in, OutputWriter out) {
		this.out = out;
		int n = in.readInt();
		out.println((long)Math.pow(getAns(0, n-1, computePoints(in, n)), 2));
	}

	public double getAns(int start, int end, Point[] points) {
		if (start == end) {
			return INF;
		}
		final int mid = (start + end) / 2;
		double d = Math.min(getAns(start, mid, points), getAns(mid + 1, end, points));
		Vector<Point> strip = new Vector<Point>();
		for (int i = start; i <= end; i++) {
			if (Math.abs(points[i].x - points[mid].x) <= d) {
				strip.add(points[i]);
			}
		}
		Collections.sort(strip, yComp);
		int size = strip.size();
		for (int i = 0; i < size; i++) {
			for (int j = i+1; j < size && (strip.get(j).y - strip.get(i).y < d); j++) {
				d = Math.min(d, strip.get(j).distance(strip.get(i)));
			}
		}
		return d;
	}

	public Point[] computePoints(InputReader in, int n) {
		int[] g = new int[n];
		Point[] points = new Point[n];
		for (int i = 0; i < n; i++) {
			g[i] = in.readInt();
			if (i > 0) {
				g[i] += g[i-1];
			}
			points[i] = new Point(i, g[i]);
		}
		Arrays.sort(points, xComp);
		return points;
	}
}

class OutputWriter {
    private PrintWriter output;
    public OutputWriter() {
        this(System.out);
    }
    public OutputWriter(OutputStream out) {
        output = new PrintWriter(out);
    }
    public OutputWriter(Writer writer) {
        output = new PrintWriter(writer);
    }

	public void println(Object... o) {
        output.print(o[0]);
        for(int i=1; i<o.length; i++) output.print(" "+o[i]);
    }

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

class InputReader {
    private BufferedReader input;
    private StringTokenizer line = new StringTokenizer("");
    public InputReader() {
        this(System.in);
    }
    public InputReader(InputStream in) {
        input = new BufferedReader(new InputStreamReader(in));
    }
    public InputReader(String s) {
        try {
            input = new BufferedReader(new FileReader(s));
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }
    public void fill() {
        try {
            if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }

	public int readInt() {
        fill();
        return Integer.parseInt(line.nextToken());
    }
}


import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Arrays;
import java.awt.geom.Point2D;
import java.util.Vector;
import java.awt.Point;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Agostinho Junior (junior94)
 */
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);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
	final long INF = Long.MAX_VALUE;

	Comparator<Point> xComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return Long.compare(o1.x, o2.x);
		}
	};
	Comparator<Point> yComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return Long.compare(o1.y, o2.y);
		}
	};

    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int n = in.readInt();
		out.println((long)Math.pow(getAns(0, n-1, computePoints(in, n)), 2));
	}

	public double getAns(int start, int end, Point[] points) {
		if (start == end) {
			return INF;
		}
		int mid = (start + end) / 2;
		double d = Math.min(getAns(start, mid, points), getAns(mid + 1, end, points));
		Vector<Point> strip = new Vector<Point>();
		for (int i = start; i < mid; i++) {
			if (points[mid].x - points[i].x < d) {
				strip.add(points[i]);
			}
		}
		strip.add(points[mid]);
		for (int i = mid + 1; i <= end; i++) {
			if (points[i].x - points[mid].x < d) {
				strip.add(points[i]);
			}
		}
		Collections.sort(strip, yComp);
		int size = strip.size();
		for (int i = 0; i < size; i++) {
			for (int j = i+1; j < Math.min(i+8, size); j++) {
				d = Math.min(d, points[i].distance(points[j]));
			}
		}
		return d;
	}

	public Point[] computePoints(InputReader in, int n) {
		int[] g = new int[n];
		Point[] points = new Point[n];
		for (int i = 0; i < n; i++) {
			g[i] = in.readInt();
			if (i > 0) {
				g[i] += g[i-1];
			}
			points[i] = new Point(i, g[i]);
		}
		Arrays.sort(points, xComp);
		return points;
	}
}

class InputReader {
    private BufferedReader input;
    private StringTokenizer line = new StringTokenizer("");
    public InputReader() {
        this(System.in);
    }
    public InputReader(InputStream in) {
        input = new BufferedReader(new InputStreamReader(in));
    }
    public InputReader(String s) {
        try {
            input = new BufferedReader(new FileReader(s));
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }
    public void fill() {
        try {
            if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }

	public int readInt() {
        fill();
        return Integer.parseInt(line.nextToken());
    }
}

class OutputWriter {
    private PrintWriter output;
    public OutputWriter() {
        this(System.out);
    }
    public OutputWriter(OutputStream out) {
        output = new PrintWriter(out);
    }
    public OutputWriter(Writer writer) {
        output = new PrintWriter(writer);
    }

	public void println(Object... o) {
        output.print(o[0]);
        for(int i=1; i<o.length; i++) output.print(" "+o[i]);
    }

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


import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Arrays;
import java.awt.geom.Point2D;
import java.util.Vector;
import java.awt.Point;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Agostinho Junior (junior94)
 */
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);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
	OutputWriter out;

	final long INF = Integer.MAX_VALUE;

	Comparator<Point> xComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.x - o2.x;
		}
	};
	Comparator<Point> yComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.y - o2.y;
		}
	};

    public void solve(int testNumber, InputReader in, OutputWriter out) {
		this.out = out;
		int n = in.readInt();
		out.println((long)Math.pow(getAns(0, n-1, computePoints(in, n)), 2));
	}

	public double getAns(int start, int end, Point[] points) {
		if (start == end) {
			return INF;
		}
		final int mid = (start + end) / 2;
		double d = Math.min(getAns(start, mid, points), getAns(mid + 1, end, points));
		Vector<Point> strip = new Vector<Point>();
		for (int i = start; i <= end; i++) {
			if (Math.abs(points[i].x - points[mid].x) <= d) {
				strip.add(points[i]);
			}
		}
		Collections.sort(strip, yComp);
		int size = strip.size();
		for (int i = 0; i < size; i++) {
			for (int j = i+1; j < size && (strip.get(j).y - strip.get(i).y < d); j++) {
				d = Math.min(d, strip.get(j).distance(strip.get(i)));
			}
		}
		return d;
	}

	public Point[] computePoints(InputReader in, int n) {
		int[] g = new int[n];
		Point[] points = new Point[n];
		for (int i = 0; i < n; i++) {
			g[i] = in.readInt();
			if (i > 0) {
				g[i] += g[i-1];
			}
			points[i] = new Point(i, g[i]);
		}
		Arrays.sort(points, xComp);
		return points;
	}
}

class OutputWriter {
    private PrintWriter output;
    public OutputWriter() {
        this(System.out);
    }
    public OutputWriter(OutputStream out) {
        output = new PrintWriter(out);
    }
    public OutputWriter(Writer writer) {
        output = new PrintWriter(writer);
    }

	public void println(Object... o) {
        output.print(o[0]);
        for(int i=1; i<o.length; i++) output.print(" "+o[i]);
    }

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

class InputReader {
    private BufferedReader input;
    private StringTokenizer line = new StringTokenizer("");
    public InputReader() {
        this(System.in);
    }
    public InputReader(InputStream in) {
        input = new BufferedReader(new InputStreamReader(in));
    }
    public InputReader(String s) {
        try {
            input = new BufferedReader(new FileReader(s));
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }
    public void fill() {
        try {
            if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }

	public int readInt() {
        fill();
        return Integer.parseInt(line.nextToken());
    }
}


import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Arrays;
import java.awt.geom.Point2D;
import java.util.Vector;
import java.awt.Point;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Agostinho Junior (junior94)
 */
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);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
	OutputWriter out;

	final long INF = Long.MAX_VALUE;

	Comparator<Point> xComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.x - o2.x;
		}
	};
	Comparator<Point> yComp = new Comparator<Point>() {
		public int compare(Point o1, Point o2) {
			return o1.y - o2.y;
		}
	};

    public void solve(int testNumber, InputReader in, OutputWriter out) {
		this.out = out;
		int n = in.readInt();
		out.println((long)Math.round(Math.pow(getAns(0, n-1, computePoints(in, n)), 2)));
	}

	public double getAns(int start, int end, Point[] points) {
		if (start == end) {
			return INF;
		}
		final int mid = (start + end) / 2;
		double d = Math.min(getAns(start, mid, points), getAns(mid + 1, end, points));
		Vector<Point> strip = new Vector<Point>();
		for (int i = start; i <= end; i++) {
			if (Math.abs(points[i].x - points[mid].x) <= d) {
				strip.add(points[i]);
			}
		}
		Collections.sort(strip, yComp);
		int size = strip.size();
		for (int i = 0; i < size; i++) {
			for (int j = i+1; j < size && (strip.get(j).y - strip.get(i).y < d); j++) {
				d = Math.min(d, strip.get(j).distance(strip.get(i)));
			}
		}
		return d;
	}

	public Point[] computePoints(InputReader in, int n) {
		int[] g = new int[n];
		Point[] points = new Point[n];
		for (int i = 0; i < n; i++) {
			g[i] = in.readInt();
			if (i > 0) {
				g[i] += g[i-1];
			}
			points[i] = new Point(i, g[i]);
		}
		Arrays.sort(points, xComp);
		return points;
	}
}

class OutputWriter {
    private PrintWriter output;
    public OutputWriter() {
        this(System.out);
    }
    public OutputWriter(OutputStream out) {
        output = new PrintWriter(out);
    }
    public OutputWriter(Writer writer) {
        output = new PrintWriter(writer);
    }

	public void println(Object... o) {
        output.print(o[0]);
        for(int i=1; i<o.length; i++) output.print(" "+o[i]);
    }

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

class InputReader {
    private BufferedReader input;
    private StringTokenizer line = new StringTokenizer("");
    public InputReader() {
        this(System.in);
    }
    public InputReader(InputStream in) {
        input = new BufferedReader(new InputStreamReader(in));
    }
    public InputReader(String s) {
        try {
            input = new BufferedReader(new FileReader(s));
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }
    public void fill() {
        try {
            if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
        } catch(IOException io) { io.printStackTrace(); System.exit(0);}
    }

	public int readInt() {
        fill();
        return Integer.parseInt(line.nextToken());
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int[] a = IOUtils.readIntArray(in, n);
        for (int i = 1; i < n; ++i) a[i] += a[i - 1];
        long best = 1 + (a[0] - a[1]) * (a[0] - a[1]);
        for (int len = 1; len < 500; ++len) {
            long sqdist = (long) (Math.sqrt(best) + 1);
            if (sqdist <= len) break;
            //System.out.println(sqdist + " " + len);
            for (int j = len; j < n; ++j) {
                long d = (long) len * len + (long) (a[j] - a[j - len]) * (a[j] - a[j - len]);
                if (d < best) best = d;
            }
        }
        out.println(best);
    }
}

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

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

    public int read() {
        // InputMismatchException -> UnknownError
        if (numChars == -1)
            throw new UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

class IOUtils {

    public static int[] readIntArray(InputReader in, int size) {
        int[] res = new int[size];
        for (int i = 0; i < size; ++i) {
            res[i] = in.readInt();
        }
        return res;
    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    int[][] buffer = new int[1001][1001];
    int[] lens = new int[1001];

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int m = in.readInt();
        int[][] mat = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                mat[i][j] = in.readInt();
            }
        }
        int lo = 0;
        int hi = (int) 1e9;
        while (lo < hi) {
            int mid = lo + (hi - lo + 1) / 2;
            if (good(mat, mid)) {
                lo = mid;
            } else {
                hi = mid - 1;
            }
        }
        out.println(lo);
    }

    private boolean good(int[][] mat, int lo) {
        int n = mat.length;
        int m = mat[0].length;
        for (int i = 0; i < n; ++i) {
            lens[i] = 0;
            for (int j = 0; j < m; ++j) {
                if (mat[i][j] >= lo) {
                    buffer[i][lens[i]] = j;
                    lens[i]++;
                }
            }
        }
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                int u = 0;
                int v = 0;
                int c = 0;
                while (u < lens[i] && v < lens[j] && c < 2) {
                    if (buffer[i][u] == buffer[j][v]) {
                        c++;
                        u++;
                        v++;
                    } else if (buffer[i][u] < buffer[j][v]) {
                        u++;
                    } else {
                        v++;
                    }
                }
                if (c == 2) return true;
            }
        }
        return false;
    }
}

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

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

    public int read() {
        // InputMismatchException -> UnknownError
        if (numChars == -1)
            throw new UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int[] a = IOUtils.readIntArray(in, n);
        for (int i = 1; i < n; ++i) a[i] += a[i - 1];
        long best = 1 + (a[0] - a[1]) * (a[0] - a[1]);
        for (int len = 1; len < 1000; ++len) {
            long sqdist = (long) (Math.sqrt(best) + 1);
            if (sqdist <= len) break;
            //System.out.println(sqdist + " " + len);
            for (int j = len; j < n; ++j) {
                long d = (long) len * len + (long) (a[j] - a[j - len]) * (a[j] - a[j - len]);
                if (d < best) best = d;
            }
        }
        out.println(best);
    }
}

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

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

    public int read() {
        // InputMismatchException -> UnknownError
        if (numChars == -1)
            throw new UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

class IOUtils {

    public static int[] readIntArray(InputReader in, int size) {
        int[] res = new int[size];
        for (int i = 0; i < size; ++i) {
            res[i] = in.readInt();
        }
        return res;
    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int[] a = IOUtils.readIntArray(in, n);
        for (int i = 1; i < n; ++i) a[i] += a[i - 1];
        long best = 1 + (a[0] - a[1]) * (a[0] - a[1]);
        for (int len = 1; len < 100; ++len) {
            long sqdist = (long) (Math.sqrt(best) + 1);
            if (sqdist <= len) break;
            //System.out.println(sqdist + " " + len);
            for (int j = len; j < n; ++j) {
                long d = (long) len * len + (long) (a[j] - a[j - len]) * (a[j] - a[j - len]);
                if (d < best) best = d;
            }
        }
        out.println(best);
    }
}

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

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

    public int read() {
        // InputMismatchException -> UnknownError
        if (numChars == -1)
            throw new UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

class IOUtils {

    public static int[] readIntArray(InputReader in, int size) {
        int[] res = new int[size];
        for (int i = 0; i < size; ++i) {
            res[i] = in.readInt();
        }
        return res;
    }

}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	return cand1.height < cand2.height;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			if (c0.size() != 0 && c0[0].height <= y) {
				y += c0[0].mass;
				c0.erase(c0.begin(), c0.begin() + 1);
				max++;
			}
			else return max;
		}
		else {
			if (c1.size() != 0 && c1[0].height <= y) {
				y += c1[0].mass;
				c1.erase(c1.begin(), c1.begin() + 1);
				max++;
			}
			else return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	return cand1.height < cand2.height;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			if (c0.size() != 0 && c0[0].height <= y) {
				y += c0[0].mass;
				c0.erase(c0.begin(), c0.begin() + 1);
				max++;
			}
			else return max;
		}
		else {
			if (c1.size() != 0 && c1[0].height <= y) {
				y += c1[0].mass;
				c1.erase(c1.begin(), c1.begin() + 1);
				max++;
			}
			else return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	freopen("INPUT.TXT", "r", stdin);
	freopen("OUTPUT.TXT", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	return cand1.height < cand2.height;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			if (c0.size() != 0 && c0[0].height <= y) {
				y += c0[0].mass;
				c0.erase(c0.begin(), c0.begin() + 1);
				max++;
			}
			else return max;
		}
		else {
			if (c1.size() != 0 && c1[0].height <= y) {
				y += c1[0].mass;
				c1.erase(c1.begin(), c1.begin() + 1);
				max++;
			}
			else return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	if (cand1.mass == cand2.mass) return cand1.height < cand2.height;
	else return cand1.mass > cand2.mass;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			bool eat = false;
			for (int i = 0; i < c0.size(); i++)
				if (c0[i].height <= y) {
					y += c0[i].mass;
					c0.erase(c0.begin() + i, c0.begin() + i + 1);
					max++;
					eat = true;
					break;
				}
			if (!eat) return max;
		}
		else {
			bool eat = false;
			for (int i = 0; i < c1.size(); i++)
				if (c1[i].height <= y) {
					y += c1[i].mass;
					c1.erase(c1.begin() + i, c1.begin() + i + 1);
					max++;
					eat = true;
					break;
				}
			if (!eat) return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	if (cand1.height == cand2.height) return cand1.mass < cand2.mass;
	else return cand1.height < cand2.height;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			if (c0.size() != 0 && c0[0].height <= y) {
				y += c0[0].mass;
				c0.erase(c0.begin(), c0.begin() + 1);
				max++;
			}
			else return max;
		}
		else {
			if (c1.size() != 0 && c1[0].height <= y) {
				y += c1[0].mass;
				c1.erase(c1.begin(), c1.begin() + 1);
				max++;
			}
			else return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

struct candy {
	int height;
	int mass;
};

bool cmp(candy cand1, candy cand2) {
	if (cand1.height == cand2.height) return cand1.mass > cand2.mass;
	else return cand1.height < cand2.height;
}

int GetMax(vector<candy> c0, vector<candy> c1, int y, int type) {
	int max = 0;
	while (true) {
		if (type == 0) {
			if (c0.size() != 0 && c0[0].height <= y) {
				y += c0[0].mass;
				c0.erase(c0.begin(), c0.begin() + 1);
				max++;
			}
			else return max;
		}
		else {
			if (c1.size() != 0 && c1[0].height <= y) {
				y += c1[0].mass;
				c1.erase(c1.begin(), c1.begin() + 1);
				max++;
			}
			else return max;
		}
		type = abs(type - 1);
	}
}

int main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);

	vector<candy> c0, c1;
	int n, x, t, h, m; cin >> n >> x;
	for (int i = 0; i < n; i++) {
		cin >> t >> h >> m;
		candy c = {h, m};
		if (t == 0) c0.push_back(c);
		else c1.push_back(c);
	}

	sort(c0.begin(), c0.end(), cmp);
	sort(c1.begin(), c1.end(), cmp);

	cout << max(GetMax(c0, c1, x, 0), GetMax(c0, c1, x, 1));

	return 0;
}


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

using namespace std;

#define forn(i,n) for (int i = int(0); i < int(n); i++)
#define forb(i,n) for (int i = int(n-1); i >= int(0); i--)
#define for1(i,n) for (int i = int(1); i <= int(n); i++)
#define fore(i,a,n) for (int i = int(a); i < int(n); i++)

#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define sz size()
#define sqr(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define all(x) x.begin(), x.end()

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

const int base = 1e9;
const int maxn = 2005;
const int MAXN = 1000;
const int logn = 20;
const int inf = 2e9;
const int alpha = 26;
const int my_hash = 31;
const long long my_mod = 2674894331;
const long long l_inf = 4e18;
const long long mod = 1e9+7;
const double pi = acos(-1.0);
const double eps = 1e-9;

int get(vector<vector<int> > &a, vector<vector<int> > &b, int x) {
	if (!a.sz) return 0;
	int ans = 0, mx, pos;
	while (true) {
		mx = 0, pos = -1;
		for (int i = 0; i < min(maxn, x + 1); i++) {
			if (!a[i].empty() && a[i].back() > mx) {
				mx = a[i].back();
				pos = i;
			}
		}
		if (pos == -1 || mx == 0) break;
		x += mx, ans++;
		a[pos].pop_back();
		mx = 0, pos = -1;
		for (int i = 0; i < min(maxn, x + 1); i++) {
			if (!b[i].empty() && b[i].back() > mx) {
				mx = b[i].back();
				pos = i;
			}
		}
		if (pos == -1 || mx == 0) break;
		x += mx, ans++;
		b[pos].pop_back();
	}
	return ans;
}

int main() {
	int n, x, ans;
	scanf("%d %d ", &n, &x);
	vector<vector<int> > a(maxn), b(maxn);
	for (int i = 0; i < n; i++) {
		int t, p, q;
		scanf("%d %d %d ", &t, &p, &q);
		if (t == 0) a[p].pb(q);
		else b[p].pb(q);
		sort(all(a[p])), sort(all(b[p]));
	}
	ans = max(get(a, b, x), get(b, a, x));
	printf("%d", ans);
}


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

using namespace std;

#define forn(i,n) for (int i = int(0); i < int(n); i++)
#define forb(i,n) for (int i = int(n-1); i >= int(0); i--)
#define for1(i,n) for (int i = int(1); i <= int(n); i++)
#define fore(i,a,n) for (int i = int(a); i < int(n); i++)

#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define sz size()
#define sqr(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define all(x) x.begin(), x.end()

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

const int base = 1e9;
const int maxn = 2005;
const int MAXN = 1000;
const int logn = 20;
const int inf = 2e9;
const int alpha = 26;
const int my_hash = 31;
const long long my_mod = 2674894331;
const long long l_inf = 4e18;
const long long mod = 1e9+7;
const double pi = acos(-1.0);
const double eps = 1e-9;

int get(vector<vector<int> > &a, vector<vector<int> > &b, int x) {
	if (!a.sz) return 0;
	int ans = 0, mx, pos;
	while (true) {
		mx = 0, pos = -1;
		for (int i = 0; i < min(maxn, x); i++) {
			if (!a[i].empty() && a[i].back() > mx) {
				mx = a[i].back();
				pos = i;
			}
		}
		if (pos == -1 || mx == 0) break;
		x += mx, ans++;
		a[pos].pop_back();
		mx = 0, pos = -1;
		for (int i = 0; i < min(maxn, x); i++) {
			if (!b[i].empty() && b[i].back() > mx) {
				mx = b[i].back();
				pos = i;
			}
		}
		if (pos == -1 || mx == 0) break;
		x += mx, ans++;
		b[pos].pop_back();
	}
	return ans;
}

int main() {
	int n, x, ans;
	scanf("%d %d ", &n, &x);
	vector<vector<int> > a(maxn), b(maxn);
	for (int i = 0; i < n; i++) {
		int t, p, q;
		scanf("%d %d %d ", &t, &p, &q);
		if (t == 0) a[p].pb(q);
		else b[p].pb(q);
		sort(all(a[p])), sort(all(b[p]));
	}
	ans = max(get(a, b, x), get(b, a, x));
	printf("%d", ans);
}


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

using namespace std;

#define forn(i,n) for (int i = int(0); i < int(n); i++)
#define forb(i,n) for (int i = int(n-1); i >= int(0); i--)
#define for1(i,n) for (int i = int(1); i <= int(n); i++)
#define fore(i,a,n) for (int i = int(a); i < int(n); i++)

#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define sz size()
#define sqr(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define all(x) x.begin(), x.end()

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

const int base = 1e9;
const int maxn = 2005;
const int MAXN = 1000;
const int logn = 20;
const int inf = 2e9;
const int alpha = 26;
const int my_hash = 31;
const long long my_mod = 2674894331;
const long long l_inf = 4e18;
const long long mod = 1e9+7;
const double pi = acos(-1.0);
const double eps = 1e-9;

struct omnom {
	int t;
	int h;
	int w;
	omnom(int t, int h, int w) :
	t(t), h(h), w(w) {}
	omnom() {}
};

int n, x, ans = 0;
vector<omnom> a;
vector<char> used;

int main() {
	scanf("%d %d ", &n, &x);
	a = vector<omnom> (n);
	for (int i = 0; i < n; i++)
		scanf("%d %d %d", &a[i].t, &a[i].h, &a[i].w);
	for (int i = 0; i < 2; i++) {
		int t = i, sum = 0, h = x;
		used = vector<char> (n, 0);
		while (true) {
			int mx = 0, pos = -1;
			for (int j = 0; j < n; j++) {
				if (used[j]) continue;
				if (a[j].t == t && a[j].h <= h && a[j].w > mx) {
					mx = a[j].w;
					pos = j;
				}
			}
			if (pos == -1) break;
			sum++;
			h += a[pos].w;
			used[pos] = 1;
			t ^= 1;
		}
		ans = max(ans, sum);
	}
	printf("%d", ans);
}


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

using namespace std;

#define forn(i,n) for (int i = int(0); i < int(n); i++)
#define forb(i,n) for (int i = int(n-1); i >= int(0); i--)
#define for1(i,n) for (int i = int(1); i <= int(n); i++)
#define fore(i,a,n) for (int i = int(a); i < int(n); i++)

#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define sz size()
#define sqr(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define all(x) x.begin(), x.end()

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

const int base = 1e9;
const int maxn = 3005;
const int MAXN = 1000;
const int logn = 20;
const int inf = 2e9;
const int alpha = 26;
const int my_hash = 31;
const long long my_mod = 2674894331;
const long long l_inf = 4e18;
const long long mod = 1e9+7;
const double pi = acos(-1.0);
const double eps = 1e-9;

int get(vector<pair<int,int> > &a, vector<pair<int,int> > &b, int x) {
	if (!a.sz) return 0;
	int ans = 0, i = 0, j = 0;
	while (i < a.sz || j < b.sz) {
		if (i < a.sz && a[i].fr <= x) {
			ans++;
			x += a[i].sc;
			i++;
		}
		else break;
		if (j < b.sz && b[j].fr <= x) {
			ans++;
			x += b[j].sc;
			j++;
		}
		else break;
	}
	return ans;
}

int main() {
	int n, x, ans;
	scanf("%d %d ", &n, &x);
	vector<pair<int,int> > a, b;
	for (int i = 0; i < n; i++) {
		int t, p, q;
		scanf("%d %d %d ", &t, &p, &q);
		if (t == 0) a.pb(mp(p, q));
		else b.pb(mp(p, q));
	}
	sort(all(a)), sort(all(b));
	ans = max(get(a, b, x), get(b, a, x));
	printf("%d", ans);
}


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#pragma comment (linker, "/STACK:16777216")

using namespace std;

int com (const void* a, const void* b){
	return *(int *)a - *(int *)b;
}

int main (void){
	//freopen("i.txt","r",stdin);
	//freopen("o.txt", "w+", stdout);

	int n, x, a[2000][3]={0}, i, z, rez=0, t=0;

	scanf("%d%d", &n,&x);

	for(i=1; i<=n; i++){
		scanf("%d%d%d", &a[i][0], &a[i][1], &a[i][2]);
		if(a[i][1]<=x) if(a[i][1]<=x && a[i][2]>a[t][2]) t=i;
	}

	if(x>=a[t][1]) {
		rez++; z=1-a[t][0]; a[t][0]=2; x+=a[t][2];
		while(1){
			t=-1;
			for(i=1; i<=n; i++) if(a[i][0]==z && a[i][1]<=x) t=i;
			for(i=i++; i<=n; i++) if(a[i][0]==z && a[i][1]<=x && a[i][2]>a[t][2]) t=i;
			if(a[t][1]<=x && t!=-1) {
				rez++;
				x+=a[t][2];
				a[t][0]=2;
				z=1-z;
			}
			else break;
		}

	}
	printf("%d", rez);
}


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#pragma comment (linker, "/STACK:16777216")

using namespace std;

int com (const void* a, const void* b){
	return *(int *)a - *(int *)b;
}

int main (void){
	//freopen("i.txt","r",stdin);
	//freopen("o.txt", "w+", stdout);

	int n, x, a[2000][3], i, z, rez=0, t=0;

	scanf("%d%d", &n,&x);
	a[0][0]=0; a[0][1]=0; a[0][2]=0;

	for(i=1; i<=n; i++){
		scanf("%d%d%d", &a[i][0], &a[i][1], &a[i][2]);
		if(a[i][1]<=x && a[i][2]>a[t][2]) t=i;
	}

	if(x>=a[t][1] && t!=0) {
		rez++; z=1-a[t][0]; a[t][0]=2; x+=a[t][2];
		while(1){
			t=-1;
			for(i=1; i<=n; i++) if(a[i][0]==z && a[i][1]<=x) { t=i; break; }
			for(i++; i<=n; i++) if(a[i][0]==z && a[i][1]<=x) if(a[i][2]>a[t][2]) t=i;
			if(t!=-1) {
				rez++;
				x+=a[t][2];
				a[t][0]=2;
				z=1-z;
			}
			else break;
		}

	}
	printf("%d", rez);
}


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#pragma comment (linker, "/STACK:16777216")

using namespace std;

int com (const void* a, const void* b){
	return *(int *)a - *(int *)b;
}

int main (void){
	//freopen("i.txt","r",stdin);
	//freopen("o.txt", "w+", stdout);

	int n, x, a[2000][3], i, z, rez=0, t=0;

	scanf("%d%d", &n,&x);

	for(i=0; i<n; i++){
		scanf("%d%d%d", &a[i][0], &a[i][1], &a[i][2]);
		if(a[i][1]<=x) if(a[i][1]<x && a[i][2]>a[t][2]) t=i;
	}

	if(x>=a[t][1]) {
		rez++; z=1-a[t][0]; a[t][0]=2; x+=a[t][2];
		while(1){
			t=-1;
			for(i=0; i<n; i++) if(a[i][0]==z && a[i][1]<=x) t=i;
			for(i=i++; i<n; i++) if(a[i][0]==z && a[i][1]<=x && a[i][2]>a[t][2]) t=i;
			if(a[t][1]<=x && t!=-1) {
				rez++;
				x+=a[t][2];
				a[t][0]=2;
				z=1-z;
			}
			else break;
		}

	}
	printf("%d", rez);
}


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#pragma comment (linker, "/STACK:16777216")

using namespace std;

int com (const void* a, const void* b){
	return *(int *)a - *(int *)b;
}

int main (void){
	//freopen("i.txt","r",stdin);
	//freopen("o.txt", "w+", stdout);

}


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#pragma comment (linker, "/STACK:16777216")

using namespace std;

int com (const void* a, const void* b){
	return *(int *)a - *(int *)b;
}

int main (void){
	//freopen("i.txt","r",stdin);
	//freopen("o.txt", "w+", stdout);

	int n, x, a[2010][3], i, z, rez=0, t=0;

	scanf("%d%d", &n,&x);
	a[0][0]=0; a[0][1]=0; a[0][2]=0;

	for(i=1; i<=n; i++){
		scanf("%d%d%d", &a[i][0], &a[i][1], &a[i][2]);
		if(a[i][1]<=x && a[i][2]>a[t][2]) t=i;
	}

	if(x>=a[t][1] && t!=0) {
		rez++; z=1-a[t][0]; a[t][0]=2; x+=a[t][2];
		while(1){
			t=0;
			for(i=1; i<=n; i++) if(a[i][0]==z && a[i][1]<=x) { t=i; break; }
			for(i++; i<=n; i++) if(a[i][0]==z && a[i][1]<=x) if(a[i][2]>a[t][2]) t=i;
			if(t) {
				rez++;
				x+=a[t][2];
				a[t][0]=2;
				z=1-z;
			}
			else break;
		}

	}
	printf("%d", rez);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define Sort(a,b) sort (a.begin(), a.end(), b)
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;
typedef pair<int,int> pii;

bool cmp (const pii& a, const pii& b){
    return !((a.first > b.first) || (a.first == b.first && a.second < b.second));
}

int main (){
 //   start;
    int n, x;
    cin >> n >> x;
    vpii t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    Sort (t[0], cmp);
    Sort (t[1], cmp);
    int type = 0;
    int _x = x, c = 0, _c = 0;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > x || e[type][p[type]]) break;
        c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= x; h++)
            if (t[type][h].second > t[type][m].second && !e[type][h]) m = h;
        x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    type = 1;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n, false);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > x || e[type][p[type]]) break;
        _c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= x; h++)
            if (t[type][h].second > t[type][m].second  && !e[type][h]) m = h;
        x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    cout << max (c, _c);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;

int main (){
  //  start;
    int n, x;
    cin >> n >> x;
    vpii t[2], _t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    _sort (t[0]);
    _sort (t[1]);
    _t[0] = t[0];
    _t[1] = t[1];
    int p[2] = {0, 0}, _p[2] = {0, 0};
    int type = 0;
    int _x = x, c = 0, _c = 0;
    while ((p[0] < (t[0].size()) || p[1] < t[1].size()) && p[type] < t[type].size()){
        if (t[type][p[type]].first > x) break;
        c++;
        x+=t[type][p[type]].second;
        p[type]++;
        type = (type + 1) % 2;
    }
    type = 1;
    while ((_p[0] < (_t[0].size()) || _p[1] < _t[1].size()) && _p[type] < _t[type].size()){
        if (_t[type][_p[type]].first > _x) break;
        _c++;
        _x+=_t[type][_p[type]].second;
        _p[type]++;
        type = (type + 1) % 2;
    }
    cout << max (_c, c);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define Sort(a,b) sort (a.begin(), a.end(), b)
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;
typedef pair<int,int> pii;

bool cmp (const pii& a, const pii& b){
    return !((a.first > b.first) || (a.first == b.first && a.second < b.second));
}

int main (){
  //  start;
    int n, x;
    cin >> n >> x;
    vpii t[2], _t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    Sort (t[0], cmp);
    Sort (t[1], cmp);
    _t[0] = t[0];
    _t[1] = t[1];
    int p[2] = {0, 0}, _p[2] = {0, 0};
    int type = 0;
    int _x = x, c = 0, _c = 0;
    while (p[type] < t[type].size()){
        if (t[type][p[type]].first > x) break;
        c++;
        x+=t[type][p[type]].second;
        p[type]++;
        type = (type + 1) % 2;
    }
    type = 1;
    while (_p[type] < _t[type].size()){
        if (_t[type][_p[type]].first > _x) break;
        _c++;
        _x+=_t[type][_p[type]].second;
        _p[type]++;
        type = (type + 1) % 2;
    }
    cout << max (_c, c);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define Sort(a,b) sort (a.begin(), a.end(), b)
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;
typedef pair<int,int> pii;

bool cmp (const pii& a, const pii& b){
    return !((a.first > b.first) || (a.first == b.first && a.second < b.second));
}

int main (){
   // start;
    int n, x;
    cin >> n >> x;
    vpii t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    Sort (t[0], cmp);
    Sort (t[1], cmp);
    int type = 0;
    int _x = x, c = 0, _c = 0;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > x || e[type][p[type]]) break;
        c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= x; h++)
            if (t[type][h].second > t[type][m].second && !e[type][h]) m = h;
        x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    type = 1;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n, false);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > _x || e[type][p[type]]) break;
        _c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= _x; h++)
            if (t[type][h].second > t[type][m].second  && !e[type][h]) m = h;
        _x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    cout << max (c, _c);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define Sort(a,b) sort (a.begin(), a.end(), b)
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;
typedef pair<int,int> pii;

bool cmp (const pii& a, const pii& b){
    return !((a.first > b.first) || (a.first == b.first && a.second < b.second));
}

int main (){
  //  start;
    int n, x;
    cin >> n >> x;
    vpii t[2], _t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    Sort (t[0], cmp);
    Sort (t[1], cmp);
    _t[0] = t[0];
    _t[1] = t[1];
    int p[2] = {0, 0}, _p[2] = {0, 0};
    int type = 0;
    int _x = x, c = 0, _c = 0;
    while ((p[0] < (t[0].size()) || p[1] < t[1].size()) && p[type] < t[type].size()){
        if (t[type][p[type]].first > x) break;
        c++;
        x+=t[type][p[type]].second;
        p[type]++;
        type = (type + 1) % 2;
    }
    type = 1;
    while ((_p[0] < (_t[0].size()) || _p[1] < _t[1].size()) && _p[type] < _t[type].size()){
        if (_t[type][_p[type]].first > _x) break;
        _c++;
        _x+=_t[type][_p[type]].second;
        _p[type]++;
        type = (type + 1) % 2;
    }
    cout << max (_c, c);
}


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <math.h>
#include <set>
#include <numeric>

#define rep(a,b,c) for(long int a = b; a < c; a++)
#define repd(a,b,c) for(long int a = b; a >= c; a--)
#define _sort(a) sort (a.begin(), a.end())
#define Sort(a,b) sort (a.begin(), a.end(), b)
#define length(s) s.size()
#define start freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define mp make_pair
typedef long long int lli;
typedef std::vector<int> vi;
typedef std::vector<lli> vli;
typedef std::vector<bool> vb;
typedef std::vector<std::string> vs;

using namespace std;

typedef vector <pair <int, int>> vpii;
typedef pair<int,int> pii;

bool cmp (const pii& a, const pii& b){
    return !((a.first > b.first) || (a.first == b.first && a.second < b.second));
}

int main (){
   // start;
    int n, x;
    cin >> n >> x;
    vpii t[2];
    rep (i, 0, n){
        int a, b, c;
        cin >> a >> b >> c;
        t[a].push_back (mp (b, c));
    }
    t[0].push_back (mp (int (1e7), 0));
    t[1].push_back (mp (int (1e7), 0));
    Sort (t[0], cmp);
    Sort (t[1], cmp);
    int type = 0;
    int _x = x, c = 0, _c = 0;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > x || e[type][p[type]]) break;
        c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= x; h++)
            if (t[type][h].second > t[type][m].second && !e[type][h]) m = h;
        x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    type = 1;
    {
    vb e[2];
    rep (i, 0, 2) e[i].resize (n, false);
    int p[2] = {0, 0};
    while (p[type] < t[type].size()){
        while (e[type][p[type]] && p[type] < t[type].size() - 1) p[type]++;
        if (t[type][p[type]].first > x || e[type][p[type]]) break;
        _c++;
        int m = p[type];
        for (int h = m; h < t[type].size() && t[type][h].first <= x; h++)
            if (t[type][h].second > t[type][m].second  && !e[type][h]) m = h;
        x+=t[type][m].second;
        e[type][m] = true;
        type = (type + 1) % 2;
    }
    }
    cout << max (c, _c);
}


#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <string>
#include <iostream>
#include <iterator>
#include <functional>
using namespace std;

class candy {
public:
	candy(int tt, int hh, int mm) : t(tt), h(hh), m(mm) {}
	int t;
	int h;
	int m;
};
int main() {
	int n, x;
	cin>>n>>x;

	list<candy> cIn;
	for (int i(0); i < n; ++i) {
		int t, h, m;
		cin>>t>>h>>m;
		cIn.push_back(candy(t, h, m));
	}
	int finalEat(0);
	for (int type(0); type<=1; ++type) {
		list<candy> c(cIn);
		int eat(0);
		int last(-1);
		for (int i(0); i < n; ++i) {
			int maxMass(INT_MIN);
			auto maxc = c.end();;
			for (auto j = c.begin(); j != c.end(); ++j) {
				if (j->t == last) continue;
				if (j->h > x) continue;
				if (j->m > maxMass) {
					maxc = j;
					maxMass = maxc->m;
				}
			}
			if (maxc == c.end()) break;
			last = maxc->t;
			x += maxc->m;
			eat++;
			c.erase(maxc);
		}
		finalEat = max(finalEat, eat);
	}
	cout<<finalEat<<endl;

	return 0;
}


#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <string>
#include <iostream>
#include <iterator>
#include <functional>
using namespace std;

class candy {
public:
	candy(int tt, int hh, int mm) : t(tt), h(hh), m(mm) {}
	int t;
	int h;
	int m;
};
int main() {
	int n, X;
	cin>>n>>X;

	list<candy> cIn;
	for (int i(0); i < n; ++i) {
		int t, h, m;
		cin>>t>>h>>m;
		cIn.push_back(candy(t, h, m));
	}
	int finalEat(0);
	for (int type(0); type<=1; ++type) {
		int x(X);
		list<candy> c(cIn);
		int eat(0);
		int last(type);
		for (int i(0); i < n; ++i) {
			int maxMass(INT_MIN);
			auto maxc = c.end();;
			for (auto j = c.begin(); j != c.end(); ++j) {
				if (j->t == last) continue;
				if (j->h > x) continue;
				if (j->m > maxMass) {
					maxc = j;
					maxMass = maxc->m;
				}
			}
			if (maxc == c.end()) break;
			last = maxc->t;
			x += maxc->m;
			eat++;
			c.erase(maxc);
		}
		cout<<eat<<endl;
		finalEat = max(finalEat, eat);
	}
	cout<<finalEat<<endl;

	return 0;
}


#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <string>
#include <iostream>
#include <iterator>
#include <functional>
using namespace std;

class candy {
public:
	candy(int tt, int hh, int mm) : t(tt), h(hh), m(mm) {}
	int t;
	int h;
	int m;
};
int main() {
	int n, X;
	cin>>n>>X;

	list<candy> cIn;
	for (int i(0); i < n; ++i) {
		int t, h, m;
		cin>>t>>h>>m;
		cIn.push_back(candy(t, h, m));
	}
	int finalEat(0);
	for (int type(0); type<=1; ++type) {
		int x(X);
		list<candy> c(cIn);
		int eat(0);
		int last(type);
		for (int i(0); i < n; ++i) {
			int maxMass(INT_MIN);
			auto maxc = c.end();;
			for (auto j = c.begin(); j != c.end(); ++j) {
				if (j->t == last) continue;
				if (j->h > x) continue;
				if (j->m > maxMass) {
					maxc = j;
					maxMass = maxc->m;
				}
			}
			if (maxc == c.end()) break;
			last = maxc->t;
			x += maxc->m;
			eat++;
			c.erase(maxc);
		}
		finalEat = max(finalEat, eat);
	}
	cout<<finalEat<<endl;

	return 0;
}


#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <string>
#include <iostream>
#include <iterator>
#include <functional>
using namespace std;

class candy {
public:
	candy(int tt, int hh, int mm) : t(tt), h(hh), m(mm) {}
	int t;
	int h;
	int m;
};
int main() {
	int n, x;
	cin>>n>>x;

	list<candy> cIn;
	for (int i(0); i < n; ++i) {
		int t, h, m;
		cin>>t>>h>>m;
		cIn.push_back(candy(t, h, m));
	}
	int finalEat(0);
	for (int type(0); type<=1; ++type) {
		list<candy> c(cIn);
		int eat(0);
		int last(type);
		for (int i(0); i < n; ++i) {
			int maxMass(INT_MIN);
			auto maxc = c.end();;
			for (auto j = c.begin(); j != c.end(); ++j) {
				if (j->t == last) continue;
				if (j->h > x) continue;
				if (j->m > maxMass) {
					maxc = j;
					maxMass = maxc->m;
				}
			}
			if (maxc == c.end()) break;
			last = maxc->t;
			x += maxc->m;
			eat++;
			c.erase(maxc);
		}
		finalEat = max(finalEat, eat);
	}
	cout<<finalEat<<endl;

	return 0;
}


#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <string>
#include <iostream>
#include <iterator>
#include <functional>
using namespace std;

class candy {
public:
	candy(int tt, int hh, int mm) : t(tt), h(hh), m(mm) {}
	int t;
	int h;
	int m;
};
int main() {
	int n, x;
	cin>>n>>x;

	list<candy> c;
	for (int i(0); i < n; ++i) {
		int t, h, m;
		cin>>t>>h>>m;
		c.push_back(candy(t, h, m));
	}

	int eat(0);
	int last(-1);
	for (int i(0); i < n; ++i) {
		int maxMass(INT_MIN);
		list<candy>::iterator maxc = c.end();;
		for (auto j = c.begin(); j != c.end(); ++j) {
			if (j->t == last) continue;
			if (j->h > x) continue;
			if (j->m > maxMass) {
				maxc = j;
				maxMass = maxc->m;
			}
		}
		if (maxc == c.end()) break;
		last = maxc->t;
		x += maxc->m;
		eat++;
		c.erase(maxc);
	}

	cout<<eat<<endl;

	return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-9
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m, n, x, k, w;
vpii con1, con2;
void init()
{
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int q, t, t1;
        cin >> q >> t >> t1;
        if (q)
            con1.push_back(pii(t, -t1));
        else
            con2.push_back(pii(t, -t1));
    }
    con1.push_back(pii(1000000000, 0));
    con2.push_back(pii(1000000000, 0));
    sort(con1.begin(), con1.end());
    sort(con2.begin(), con2.end());
}
int fun(int q, int tx)
{
    int c = 0, l = 0, r = 0;
    while(true)
    {
        if (q)
        {
            if (tx <= con1[l].first)
                break;
            tx -= con1[l++].second;
        }
        else
        {
            if (tx <= con2[r].first)
                break;
            tx -= con2[r++].second;
        }
        c++;
        q ^= 1;
    }
    return c;
}
void solve()
{
    int ot = 0;
    ot = max(ot, fun(0, x));
    ot = max(ot, fun(1, x));
    cout << ot;
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-9
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m, n, x, k, w;
vpii con1, con2;
void init()
{
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int q, t, t1;
        cin >> q >> t >> t1;
        if (q)
            con1.push_back(pii(t, -t1));
        else
            con2.push_back(pii(t, -t1));
    }
    con1.push_back(pii(1000000000, 0));
    con2.push_back(pii(1000000000, 0));
    sort(con1.begin(), con1.end());
    sort(con2.begin(), con2.end());
}
int fun(int q, int tx)
{
    int c = 0, l = 0, r = 0;
    while(true)
    {
        if (q)
        {
            if (tx < con1[l].first)
                break;
            tx -= con1[l++].second;
        }
        else
        {
            if (tx < con2[r].first)
                break;
            tx -= con2[r++].second;
        }
        c++;
        q ^= 1;
    }
    return c;
}
void solve()
{
    int ot = 0;
    ot = max(ot, fun(0, x));
    ot = max(ot, fun(1, x));
    cout << ot;
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-9
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m, n, x, k, w;
vvpii con;
void init()
{
    con.resize(2);
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int q, t, t1;
        cin >> q >> t >> t1;
        con[q].push_back(pii(t, t1));
    }
}
void solve()
{
    int ot = 0, ot1 = 0, tx = x, q = 0;
    while(true)
    {
        int id = -1, ms = 0;
        for (int i = 0; i < con[q].size(); ++i)
        {
            if (tx < con[q][i].first)
                continue;
            if (con[q][i].second > ms)
            {
                ms = con[q][i].second;
                id = i;
            }
        }
        if (id == -1)
            break;
        tx += ms;
        con[q][id].second *= -1;
        q ^= 1;
        ot1++;

    }
    tx = x, q = 1;
    for (int j = 0; j < 2; ++j)
        for (int i = 0; i < con[q].size(); ++i)
            con[j][i].second = abs(con[j][i].second);
    while(true)
    {
        int id = -1, ms = 0;
        for (int i = 0; i < con[q].size(); ++i)
        {
            if (tx < con[q][i].first)
                continue;
            if (con[q][i].second > ms)
            {
                ms = con[q][i].second;
                id = i;
            }
        }
        if (id == -1)
            break;
        tx += ms;
        con[q][id].second *= -1;
        q ^= 1;
        ot++;
    }
    cout << max(ot, ot1);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-9
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m, n, x, k, w;
vvpii con;
void init()
{
    con.resize(2);
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int q, t, t1;
        cin >> q >> t >> t1;
        con[q].push_back(pii(t, t1));
    }
}
void solve()
{
    int ot = 0, ot1 = 0, tx = x, q = 0;
    while(true)
    {
        int id = -1, ms = 0;
        for (int i = 0; i < con[q].size(); ++i)
        {
            if (tx < con[q][i].first)
                continue;
            if (con[q][i].second > ms)
            {
                ms = con[q][i].second;
                id = i;
            }
        }
        if (id == -1)
            break;
        tx += ms;
        con[q][id].second *= -1;
        q ^= 1;
        ot1++;

    }
    tx = x, q = 1;
    for (int j = 0; j < 2; ++j)
        for (int i = 0; i < con[j].size(); ++i)
            con[j][i].second = abs(con[j][i].second);
    while(true)
    {
        int id = -1, ms = 0;
        for (int i = 0; i < con[q].size(); ++i)
        {
            if (tx < con[q][i].first)
                continue;
            if (con[q][i].second > ms)
            {
                ms = con[q][i].second;
                id = i;
            }
        }
        if (id == -1)
            break;
        tx += ms;
        con[q][id].second *= -1;
        q ^= 1;
        ot++;
    }
    cout << max(ot, ot1);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-10
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m[2000], n, x;
vpii a, b;
void init()
{
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int t;
        cin >> t;
        pii tb;
        cin >> tb.first >> tb.second;
        tb.second = -tb.second;
        if (t)
            a.push_back(tb);
        else
            b.push_back(tb);
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
}
void solve()
{
    int tx = x, ot1 = 0, ot2 = 0;
    int tr = min(a.size(), b.size());
    for (int i = 0; i < tr; ++i)
    {
        if (tx >= a[i].first)
        {
            tx -= a[i].second;
            ot1++;
        }
        else
            break;
        if (tx >= b[i].first)
        {
            tx -= b[i].second;
            ot1++;
        }
        else
            break;
    }
    if (a.size() > tr)
        if (tx >= a[tr].first)
            ot1++;
    tx = x;
    for (int i = 0; i < min(a.size(), b.size()); ++i)
    {
        if (tx >= b[i].first)
        {
            tx -= b[i].second;
            ot2++;
        }
        else
            break;
        if (tx >= a[i].first)
        {
            tx -= a[i].second;
            ot2++;
        }
        else
            break;
    }
    if (b.size() > tr)
        if (tx >= b[tr].first)
            ot2++;
    cout << max(ot1, ot2);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-10
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m[2000], n, x;
vpii a, b;
void init()
{
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int t;
        cin >> t;
        pii tb;
        cin >> tb.first >> tb.second;
        if (t)
            a.push_back(tb);
        else
            b.push_back(tb);
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
}
void solve()
{
    int tx = x, ot1 = 0, ot2 = 0;
    int tr = min(a.size(), b.size());
    for (int i = 0; i < tr; ++i)
    {
        if (tx >= a[i].first)
        {
            tx += a[i].second;
            ot1++;
        }
        else
            break;
        if (tx >= b[i].first)
        {
            tx += b[i].second;
            ot1++;
        }
        else
            break;
    }
    if (a.size() > tr)
        if (tx >= a[tr].first)
            ot1++;
    tx = x;
    for (int i = 0; i < min(a.size(), b.size()); ++i)
    {
        if (tx >= b[i].first)
        {
            tx += b[i].second;
            ot2++;
        }
        else
            break;
        if (tx >= a[i].first)
        {
            tx += a[i].second;
            ot2++;
        }
        else
            break;
    }
    if (b.size() > tr)
        if (tx >= b[tr].first)
            ot2++;
    cout << max(ot1, ot2);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <sstream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <memory.h>
#include <complex>
#include <numeric>
using namespace std;
#pragma comment(linker, "/STACK:256000000")
#define mp make_pair
#define pb push_back
#define all(C) (C).begin(), (C).end()
#define sz(C) (int)(C).size()
#define PRIME 1103
#define PRIME1 31415
#define INF ((1ll << 30) - 1)
#define MOD 99990001
#define FAIL ++*(int*)0
#define EPS 1e-10
template<class T> T sqr(T a) {return a * a;}
typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pi64;
typedef pair<int, pii> piii;
typedef vector<int> vi;
typedef vector<int64> vi64;
typedef vector<vi64> vvi64;
typedef vector<pi64> vpi64;
typedef vector<vpi64 > vvpi64;
typedef vector<pii> vpii;
typedef vector<vector<int> > vvi;
typedef vector<vvi> vvvi;
typedef vector<vector<pair<int, int > > > vvpii;
typedef vector<vector<vector<pair<int, int > > > > vvvpii;
typedef complex<long double> cd;
//----------------------------------------------------------
int m[2000], n, x;
vpii a, b;
void init()
{
    cin >> n >> x;
    for (int i = 0; i < n; ++i)
    {
        int t;
        cin >> t;
        pii tb;
        cin >> tb.first >> tb.second;
        if (t)
            a.push_back(tb);
        else
            b.push_back(tb);
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
}
void solve()
{
    int tx = x, ot1 = 0, ot2 = 0;
    for (int i = 0; i < min(a.size(), b.size()); ++i)
    {
        if (tx >= a[i].first)
        {
            tx += a[i].second;
            ot1++;
        }
        else
            break;
        if (tx >= b[i].first)
        {
            tx += b[i].second;
            ot1++;
        }
        else
            break;

    }
    tx = x;
    for (int i = 0; i < min(a.size(), b.size()); ++i)
    {
        if (tx >= b[i].first)
        {
            tx += b[i].second;
            ot2++;
        }
        else
            break;
        if (tx >= a[i].first)
        {
            tx += a[i].second;
            ot2++;
        }
        else
            break;
    }
    cout << max(ot1, ot2);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen ("input.txt", "r", stdin); freopen ("output.txt", "w", stdout);
    #endif
    init();
    solve();

    return 0;
}


#include<stdio.h>
#include<iostream>
#include<sstream>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<stack>
#include<string.h>
#include<string>
#include<map>
#include<algorithm>
#include<time.h>
#include<set>
#include<vector>
#include <numeric>
using namespace std;

#define All(a) a.begin(), a.end()
#define _2d(a,row,col,type) type**a=new type*[row]; for (int i=0;i<row;i++) a[i]=new type[col];
#define rep(i,n) for(int i=0;i<int(n);i++)
#define repd(i,n) for(int i=n-1;i>=0;i--)
#define repi(i,a,n) for(int i=int(a);i<int(n);i++)
#define scn(a,n) rep(i,n) cin>>a[i];
#define scn2(a,row,col) rep(i,row) rep(j,col) cin>>a[i][j];
#define prn(a,n) rep(i,n-1) cout<<a[i]<<" "; cout<<a[n-1]<<endl;
#define prn2(a,row,col) rep(i,row){rep(j,col-1) cout<<a[i][j]<<" "; cout<<a[i][col-1]<<endl;}
#define Odd(x) x%2!=0
#define Even(x) x%2==0
#define Pi 3.14
#define INF 2000000000 // 2 billion

typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<double> vd;
typedef vector<string> vs;
typedef pair<int, int> ii;
typedef pair<int, string> is;
typedef vector<ii> vii;
typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
typedef long double ld;

bool comp (pair<int, int> a, pair<int, int> b){
	return a.first<b.first;
}

int main(){
	ll n, x, res=0;
	int t, h, m;
	vii a, b;
	cin>>n>>x;
	rep(i, n){
		cin>>t>>h>>m;
		t ? a.push_back(make_pair(h, m)) : b.push_back(make_pair(h, m));
	}
	sort(All(a));
	sort(All(b));
	bool way = a.size() > b.size();
	while(true){
		if ((way && a.size() == 0) || (way && a[0].first > x)){
			cout<<res<<endl;
			return 0;
		}
		if ((!way && b.size() == 0) || (!way && b[0].first > x)){
			cout<<res<<endl;
			return 0;
		}
		int i = 0, max = -1;
		if (way){
			rep(j, a.size()){
				if (a[j].first > x) break;
				if (a[j].second > max){
					i = j;
					max = a[j].second;
				}
			}
			x += max;
			a.erase(a.begin() + i);
		}
		else{
			rep(j, b.size()){
				if (b[j].first > x) break;
				if (b[j].second > max){
					i = j;
					max = b[j].second;
				}
			}
			x += max;
			b.erase(b.begin() + i);
		}
		way = !way;
		res++;
	}
	return 0;
}


#include<stdio.h>
#include<iostream>
#include<sstream>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<stack>
#include<string.h>
#include<string>
#include<map>
#include<algorithm>
#include<time.h>
#include<set>
#include<vector>
#include <numeric>
using namespace std;

#define All(a) a.begin(), a.end()
#define _2d(a,row,col,type) type**a=new type*[row]; for (int i=0;i<row;i++) a[i]=new type[col];
#define rep(i,n) for(int i=0;i<int(n);i++)
#define repd(i,n) for(int i=n-1;i>=0;i--)
#define repi(i,a,n) for(int i=int(a);i<int(n);i++)
#define scn(a,n) rep(i,n) cin>>a[i];
#define scn2(a,row,col) rep(i,row) rep(j,col) cin>>a[i][j];
#define prn(a,n) rep(i,n-1) cout<<a[i]<<" "; cout<<a[n-1]<<endl;
#define prn2(a,row,col) rep(i,row){rep(j,col-1) cout<<a[i][j]<<" "; cout<<a[i][col-1]<<endl;}
#define Odd(x) x%2!=0
#define Even(x) x%2==0
#define Pi 3.14
#define INF 2000000000 // 2 billion

typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<double> vd;
typedef vector<string> vs;
typedef pair<int, int> ii;
typedef pair<int, string> is;
typedef vector<ii> vii;
typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
typedef long double ld;

bool comp (pair<int, int> a, pair<int, int> b){
	return a.first<b.first;
}

int main(){
	ll n, x, xx, res=0, res2=0;
	int t, h, m;
	vii a, b;
	cin>>n>>x;
	xx = x;
	rep(i, n){
		cin>>t>>h>>m;
		t ? a.push_back(make_pair(h, m)) : b.push_back(make_pair(h, m));
	}
	sort(All(a));
	sort(All(b));
	vii aa(a), bb(b);
	bool way = 1;
	while(true){
		if ((way && a.size() == 0) || (way && a[0].first > x)){
			break;
		}
		if ((!way && b.size() == 0) || (!way && b[0].first > x)){
			break;
		}
		int i = 0, max = -1;
		if (way){
			rep(j, a.size()){
				if (a[j].first > x) break;
				if (a[j].second > max){
					i = j;
					max = a[j].second;
				}
			}
			x += max;
			a.erase(a.begin() + i);
		}
		else{
			rep(j, b.size()){
				if (b[j].first > x) break;
				if (b[j].second > max){
					i = j;
					max = b[j].second;
				}
			}
			x += max;
			b.erase(b.begin() + i);
		}
		way = !way;
		res++;
	}

	way = 0;
	a = aa;
	b = bb;
	x = xx;
	while(true){
		if ((way && a.size() == 0) || (way && a[0].first > x)){
			break;
		}
		if ((!way && b.size() == 0) || (!way && b[0].first > x)){
			break;
		}
		int i = 0, max = -1;
		if (way){
			rep(j, a.size()){
				if (a[j].first > x) break;
				if (a[j].second > max){
					i = j;
					max = a[j].second;
				}
			}
			x += max;
			a.erase(a.begin() + i);
		}
		else{
			rep(j, b.size()){
				if (b[j].first > x) break;
				if (b[j].second > max){
					i = j;
					max = b[j].second;
				}
			}
			x += max;
			b.erase(b.begin() + i);
		}
		way = !way;
		res2++;
	}
	cout<<max(res, res2);
	return 0;
}


#include<stdio.h>
#include<iostream>
#include<sstream>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<stack>
#include<string.h>
#include<string>
#include<map>
#include<algorithm>
#include<time.h>
#include<set>
#include<vector>
#include <numeric>
using namespace std;

#define All(a) a.begin(), a.end()
#define _2d(a,row,col,type) type**a=new type*[row]; for (int i=0;i<row;i++) a[i]=new type[col];
#define rep(i,n) for(int i=0;i<int(n);i++)
#define repd(i,n) for(int i=n-1;i>=0;i--)
#define repi(i,a,n) for(int i=int(a);i<int(n);i++)
#define scn(a,n) rep(i,n) cin>>a[i];
#define scn2(a,row,col) rep(i,row) rep(j,col) cin>>a[i][j];
#define prn(a,n) rep(i,n-1) cout<<a[i]<<" "; cout<<a[n-1]<<endl;
#define prn2(a,row,col) rep(i,row){rep(j,col-1) cout<<a[i][j]<<" "; cout<<a[i][col-1]<<endl;}
#define Odd(x) x%2!=0
#define Even(x) x%2==0
#define Pi 3.14
#define INF 2000000000 // 2 billion

typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<double> vd;
typedef vector<string> vs;
typedef pair<int, int> ii;
typedef pair<int, string> is;
typedef vector<ii> vii;
typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
typedef long double ld;

bool comp (pair<int, int> a, pair<int, int> b){
	return a.first<b.first;
}

int main(){
	ll n, x, res=0;
	int t, h, m;
	vii a, b;
	cin>>n>>x;
	rep(i, n){
		cin>>t>>h>>m;
		t ? a.push_back(make_pair(h, m)) : b.push_back(make_pair(h, m));
	}
	sort(All(a));
	sort(All(b));
	bool way = a.size() > b.size();
	if (a.size() && b.size()) way = a[0].first < b[0].first;
	while(true){
		if ((way && a.size() == 0) || (way && a[0].first > x)){
			cout<<res<<endl;
			return 0;
		}
		if ((!way && b.size() == 0) || (!way && b[0].first > x)){
			cout<<res<<endl;
			return 0;
		}
		int i = 0, max = -1;
		if (way){
			rep(j, a.size()){
				if (a[j].first > x) break;
				if (a[j].second > max){
					i = j;
					max = a[j].second;
				}
			}
			x += max;
			a.erase(a.begin() + i);
		}
		else{
			rep(j, b.size()){
				if (b[j].first > x) break;
				if (b[j].second > max){
					i = j;
					max = b[j].second;
				}
			}
			x += max;
			b.erase(b.begin() + i);
		}
		way = !way;
		res++;
	}
	return 0;
}


#include <iostream>
#include <map>
#include <fstream>
using namespace std;

int main()
{
	ifstream ff("file.txt");
	int n, x;
	cin>>n>>x;
	multimap<int, int> m0, m1, m00, m11;
	int y;
	for(int i=0; i<n; i++)
	{
		cin>>y;
		int h, m;
		cin>>h>>m;
		if(y==0)
		{
			m0.insert(make_pair(h, m));
			m00.insert(make_pair(h, m));
		}
		else
		{
			m1.insert(make_pair(h, m));
			m11.insert(make_pair(h, m));
		}
	}
	int Z1=0, Z2=0;
	multimap<int, int>::iterator p;
	bool b1=false;
	int x1=x;
	while(true)
	{
		if(b1==false)
		{
			p = m0.find(x);
			if(p==m0.end())
			{
				p = m0.upper_bound(x);
				if(m0.size()==0)
				{
					break;
				}
				p--;
				if(p==m0.end())
				{
					break;
				}
			}
			x+=p->second;
			Z1++;
			b1=true;
			m0.erase(p);
		}
		else
		{
			p = m1.find(x);
			if(p==m1.end())
			{
				p = m1.upper_bound(x);
				if(m1.size()==0)
				{
					break;
				}
				p--;
				if(p==m1.end())
				{
					break;
				}
			}
			x+=p->second;
			Z1++;
			b1=false;
			m1.erase(p);
		}

	}
	b1=true;
	while(true)
	{
		if(b1==false)
		{
			p = m00.find(x1);
			if(p==m00.end())
			{
				p = m00.upper_bound(x1);
				if(m00.size()==0)
				{
					break;
				}
				p--;
				if(p==m00.end())
				{
					break;
				}
			}
			x1+=p->second;
			Z2++;
			b1=true;
			m00.erase(p);
		}
		else
		{
			p = m11.find(x1);
			if(p==m11.end())
			{
				p = m11.upper_bound(x1);
				if(m11.size()==0)
				{
					break;
				}
				p--;
				if(p==m11.end())
				{
					break;
				}
			}
			x1+=p->second;
			Z2++;
			b1=false;
			m11.erase(p);
		}
	}

	cout<<max(Z1, Z2)<<endl;
	return 0;
}