Problem: Example

Input

3 9
6 3
5 2
3 1
2
2
2


Output

2

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define N 100500
#define int long long
using namespace std;
struct Data{int a, b;}d[N];
bool cmp(Data x, Data y){
	return x.a - x.b > y.a - y.b;
}
int n, m, c[N], f[N], s[N], g[N], h[N], Ans, mnp, mn[N << 2], nn;
int Min(int a, int b){return g[a] <= g[b] ? a : b;}
void build(int rt, int l, int r){
	if(l == r){
		mn[rt] = l;
		//printf("g[%d] = %d\n", r, g[l]);
		return ;
	}
	int mid = (l + r) >> 1;
	build(rt << 1, l, mid);
	build(rt << 1 | 1, mid + 1, r);
	mn[rt] = Min(mn[rt << 1], mn[rt << 1 | 1]);
	//printf("%d  %d  %d  %d\n", rt, l, r, mn[rt]);
}
int qry(int rt, int l, int r, int y){
	if(l == r) return g[l] <= y ? l : (n + 1);
	int mid = (l + r) >> 1;
	if(g[mn[rt << 1]] <= y) return qry(rt << 1, l, mid, y);
	if(g[mn[rt << 1 | 1]] <= y) return qry(rt << 1 | 1, mid + 1, r, y);
	return n + 1;
}
int query(int rt, int l, int r, int x, int y){
	//printf("%d  %d  %d  %d  %d\n", rt, l, r, x, y);
	if(x <= l) return qry(rt, l, r, y);
	int mid = (l + r) >> 1, p1 = n + 1, p2;
	if(x <= mid) p1 = query(rt << 1, l, mid, x, y);
	p2 = query(rt << 1 | 1, mid + 1, r, x, y);
	//printf("%d  %d  %d  %d  %d  %d  %d  %d\n", rt, l, r, x, y, p1, p2, Min(p1, p2));
	return min(p1, p2);
}
int getsum(int x, int y){
	if(y < x) return h[y];
	return h[y] - (d[x].a - d[x].b) + (d[y + 1].a - d[y + 1].b);
}
int find(int x, int y){
	int l = 0, r = nn, mid;
	while(l <= r){
		mid = (l + r) >> 1;
		if(getsum(x, mid) >= y) r = mid - 1;
		else l = mid + 1;
	}
        if(r == nn) r = n;
	return r + 1;
}
void work(int x){
	//printf("x ====== %d\n", x);
	int pos = query(1, 1, n, x, d[x].a - d[x].b);
	pos = min(pos, mnp);
	int fin = find(x, m - d[x].a);
	//printf("fin == %d  pos == %d\n", fin, pos);
	if(pos <= fin) return ;
	Ans = min(Ans, fin + 1);
}
signed main(){
	scanf("%lld%lld", &n, &m);
	for(int i = 1; i <= n; i++)
		scanf("%lld%lld", &d[i].a, &d[i].b);
	for(int i = 1; i <= n; i++) scanf("%lld", &c[i]);
	sort(d + 1, d + n + 1, cmp);
	nn = n;
	while(d[nn].a - d[nn].b <= 0) nn--;
	for(int i = 1; i <= n; i++){
		f[i] = d[i].a - d[i].b - c[i];
		s[i] = s[i - 1] + f[i];
		g[i] = s[i] + (d[i + 1].a - d[i + 1].b);
		h[i] = d[i].a - d[i].b + h[i - 1];
	}
	g[n + 1] = INT_MAX;
	build(1, 1, n);
	mnp = n + 1;
	for(int i = 1; i <= n; i++)
		if(s[i] <= 0) {mnp = i; break;}
	Ans = LLONG_MAX;
	/*work(1);
	return 0;*/
	for(int i = 1; i <= n; i++)
		work(i);
	if(Ans == LLONG_MAX) puts("-1");
	else printf("%lld\n", Ans);
	return 0;
}