//#define anjn
//      Anjan Agarwala - anjn98

//#define opti
#ifdef opti
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,unroll-loops,fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#endif

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

typedef long long int ll;
typedef unsigned long long int ull;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

ll power(ll x,ll y,ll p){ll r=1; x=x%p; while(y){ if(y&1) r= r*x%p; y=y>>1; x=x*x%p; } return r; }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int csrand(int l=0, int r=1e9){
    uniform_int_distribution<int> uid(l, r);
    return uid(rng);
}

#define PR(x) cout<<#x<<" : "<<x<<"\n";
#define PR1(x,y) cout<<#x<<" : "<<x<<"  |  "<<#y<<" : "<<y<<"\n";
#define PR2(x,y,z) cout<<#x<<" : "<<x<<"  |  "<<#y<<" : "<<y<<"  |  "<<#z<<" : "<<z<<"\n";
#define ED cout<<'\n';

#define IO              ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define FILEIO          freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define all(v)          v.begin(),v.end()
#define endl            '\n'
#define fr1(j,n)        for(int j=0;j<n;j++)
#define fr(n)           for(int i=0;i<n;i++)
#define trav(x,s)       for(auto x:s)
#define PB              push_back
#define pii             pair<int,int>
#define pll             pair<long long int,long long int>
#define F               first
#define S               second
#define binf            2000000000000000001
#define mod             1000000007

const int N=2e5+99 ;
ll mod1=998244353;
vector<ll> a(N),st;
set<ll> off[N];

int main()
{

    IO
    #ifndef ONLINE_JUDGE
    FILEIO
    #endif

	int n,m; cin>>n>>m;
	ll hi=0;
	fr(n) cin>>a[i+1],hi+=a[i+1]+a[i+1];
	fr(m)
	{
		int d,t; cin>>d>>t;
		off[t].insert(d);
	}
	ll lo=0,mi,ans=1e9;

	while(lo<=hi)
	{
		ll mi=(lo+hi)/2;
		vector<pll> v;
		//cout<<mi<<" ";
		for(ll i=1;i<=n;i++)
		{
			auto j=off[i].upper_bound(mi);
			if(j==off[i].begin()) continue;
			j--;
			//cout<<*j<<" ";
			v.PB({*j,i});
		}
		sort(all(v));
		st=a; ll cur=0,j=0;

		for(int i=1;i<=mi;i++)
		{
			cur++;
			while(j<v.size() && v[j].F<i)j++;
			while(j<v.size() && v[j].F==i)
			{
				ll ta=min(cur,st[v[j].S]);
				cur-=ta;
				st[v[j].S]-=ta;
				j++;
			}
		}
		ll rem=0;
		fr(n) rem+=st[i+1];
		rem+=rem;

		if(cur>=rem)
			ans=min(ans,mi),hi=mi-1;
		else
			lo=mi+1;

	}
	cout<<ans<<endl;

}

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 2e5+10;
struct node{
	LL d,t;
}b[maxn];
LL a[maxn],aa[maxn],last[maxn];
vector<int>G[maxn];
int n,m;

bool cmp(node& x,node& y)
{
	if(x.d==y.d) return x.t < y.t;
	return x.d < y.d;
}

bool check(LL x)
{
	memset(last,0,sizeof(last));
	for(int i = 1;i <= n;i++)
	{
		a[i] = aa[i];
		G[i].clear();
	}
	for(int i = 0;i < m;i++)
	{
		if(b[i].d > x) break;
		last[b[i].t] = b[i].d;
	}
	for(int i = 1;i <= n;i++)
	{
		G[last[i]].push_back(i);
	}
	LL pre = 0,money = 0;
	for(int i = 0;i < m;i++)
	{
		if(b[i].d > x) break;
		if(i>0&&b[i].d==pre) continue;
		money += b[i].d - pre;
		for(int t : G[b[i].d])
		{
			if(money>=a[t])
			{
				money -= a[t];
				a[t] = 0;
			}
			else
			{
				a[t] -= money;
				money = 0;
			}
		}
		pre = b[i].d;
	}
	money += x - pre;
	for(int i = 1;i <= n;i++)
	{
		if(money>=2*a[i])
		{
			money -= 2*a[i];
			a[i] = 0;
		}
		else
		{
			return false;
		}
	}
	return true;
}

int main()
{
	cin>>n>>m;
	for(int i = 1;i <= n;i++)
	{
		cin>>aa[i];
	}
	for(int i = 0;i < m;i++)
	{
		cin>>b[i].d>>b[i].t;
	}
	sort(b,b+m,cmp);
	LL l = 0,r = 1e12;
	//check(20);
	while(l<r-1)
	{
		LL mid = l+(r-l)/2;
		if(check(mid))
		{
			r = mid;
		}
		else
		{
			l = mid;
		}
	}
	cout<<r<<endl;
}

#include<bits/stdc++.h>
#define ii pair<int,int>
#define X first
#define Y second
using namespace std;
const int N=200004;
int n,m,k[N],sum=0,need[N];
ii a[N];
bool check(int mid)
{
    for(int i=1;i<=n;i++) need[i]=k[i];
    int money=mid,now=m,all=0;
    for(int i=mid;i>=1;i--)
    {
        money=min(money,i);
        while(now>=1&&a[now].X>i) now--;
        while(now>=1&&a[now].X==i) {
            int x=need[a[now].Y];
            int y=money;
            all+=min(x,y);
            money-=min(x,y);
            need[a[now].Y]-=min(x,y);
            now--;
        }
    }
    return (all+(sum-all)*2)<=mid;
}
int main()
{
    //freopen("1165F2.INP","r",stdin);
    //freopen("1165F2.OUT","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&k[i]);
        sum+=k[i];
    }
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        a[i]=ii(x,y);
    }
    sort(a+1,a+m+1);
    int l=1,r=4e5;
    int ans=0;
    while(l<=r)
    {
        int mid=(l+r)/2;
        if(check(mid)) ans=mid,r=mid-1;
        else l=mid+1;
    }
    cout<<ans;
}

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <random>
#include <ctime>
#include <string>
#include <iomanip>
#include <set>
#include <map>
#include <queue>
#include <numeric>
#include <limits>
#include <fstream>
#include <stack>
#include <unordered_set>
#include <sstream>
#include <array>
#include <chrono>
#include <unordered_map>
#include <cassert>

using namespace std;

typedef unsigned long long uli;
typedef long long li;
typedef long double ld;
typedef pair<int, int> pii;
typedef vector<int> vi;

#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
//#define x first
//#define y second
#define pb push_back
#define mp make_pair
#define forn(i, n) for(int i = 0; i < int(n); ++i)
#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)
#define forb(i, n) for(int i = int(n) - 1; i >= 0; --i)
#define left 2 * v + 1
#define right 2 * v + 2

const int INF = 1e9 + 1000;
const li INF64 = 1e18;

const int N = 4e5 + 1000;
const int MOD = 998244353;
const double EPS = 1E-9;
const double PI = acos(-1.);

li gcd(li a, li b) {
	return a == 0 ? b : gcd(b % a, a);
}

vector<pii> t;
vector<int> k;
vector<int> lasts;
vector<vector<int>> nxt;
int n;

bool ok(int day) {
	int money = 0;

	vector<int> need = k;
	vector<int> poses(n, 0);
	int last = 0;

	for (auto e : t) {

		if (e.first > day) {
			break;
		}
		money += e.first - last;
		last = e.first;

		int type = e.second;
		int curidx = poses[type];
		poses[type]++;
		if (curidx + 1 < nxt[type].size() && nxt[type][curidx + 1] <= day) {
			continue;
		}

		if (need[e.second]) {
			assert(need[e.second] == k[e.second]);

			if (money >= need[e.second]) {
				money -= need[e.second];
				need[e.second] = 0;
			}
			else {
				need[e.second] -= money;
				money = 0;
			}
		}
	}

	money += day - last;
	int rest = 0;
	for (auto i : need) {
		rest += i * 2;
	}

	return money >= rest;

}

int main() {

#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int m;
	cin >> n >> m;

	int l = 0, r = 1e9;
	k.resize(n);
	t.resize(m);

	for (auto& i : k) {
		cin >> i;
	}

	for (auto& i : t) {
		cin >> i.first >> i.second;
		i.second--;
	}

	sort(all(t));

	lasts.resize(n, INF);
	nxt.resize(n);

	for (auto e : t) {

		int d = e.first;
		int t = e.second;

		nxt[t].push_back(d);
	}

	r = 1e9;
	while (r - l > 1) {
		int m = (r + l) / 2;
		if (ok(m))
			r = m;
		else
			l = m;
	}

	cout << r;

}

// end of patience
#include<bits/stdc++.h>
using namespace std ;
#define int long long int
#define F first
#define S second
#define pb push_back
int a[4000005] , b[4000005] , dp[500005] ;
vector<int> adj[500005] , v[500005] ;
int check( int k , int tot , int n )
{
    memset( dp , 0 , sizeof(dp) ) ;
    for( int i = k ; i > 0 ; i-- )
    {
        for( int j = 0 ; j < (int)adj[i].size() ; j++ )
            dp[adj[i][j]] = max( dp[adj[i][j]] , i ) ;
    }
    for( int i = 1 ; i <= n ; i++ )
    v[dp[i]].push_back(i) ;
    int cnt = 0 ;
    for( int i = 1 ; i <= k ; i++ )
    {
        cnt++ ;
        for( int j = 0 ; j < (int)v[i].size() ; j++ )
        {
            int x = v[i][j] ;
            tot -= min( cnt , a[x] ) ;
            cnt -= min( cnt , a[x] ) ;
        }
    }
    for( int i = 0 ; i < 500005 ; i++ )
        v[i].clear() ;
    if( cnt >= 2*tot )
        return 1 ;
    return 0 ;
}
signed main()
{
    ios_base::sync_with_stdio(false) ;
    cin.tie(0) ; cout.tie(0) ;
    int n , m ;
    cin >> n >> m ;
    int tot = 0 ;
    for( int i = 1 ; i <= n ; i++ )
        cin >> a[i] , tot += a[i] ;
    for( int i = 0 ; i < m ; i++ )
    {
        int x , y ;
        cin >> x >> y ;
        adj[x].push_back(y) ;
    }
    int ans ;
    int lo = 1 , hi = 5e5 ;
    while( lo <= hi )
    {
        int mid = ( lo + hi ) / 2 ;
        if( check( mid , tot , n ) )
            hi = mid - 1 , ans = mid ;
        else
            lo = mid + 1 ;
    }
    cout << ans ;
    cerr << "Time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec \n";
}

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<set>
#include<map>
#include<iterator>
#include<stack>
#include<queue>
#include<utility>
#include<functional>
#include<bitset>
#include<numeric>
#include<cstring>
#include<tuple>
using namespace std;

int n, m, sum = 0, low, mid, high, ans = 1e9;
vector< int > order( 2e5 + 5 );
vector< pair< int, int > > arr( 2e5 + 5 );

bool solve( void )
{
	int cnt = 0, money = 0, buy, pos;
	vector< int > last( 2e5 + 5, 0 );
	for( int i = 1; i <= m && arr[ i ].first <= mid; ++i )
	{
		last[ arr[ i ].second ] = i;
		pos = i;
	}
	for( int i = 1; i <= m && arr[ i ].first <= mid; ++i )
	{
		money += arr[ i ].first - arr[ i - 1 ].first;
		if( last[ arr[ i ].second ] == i )
		{
			buy = min( order[ arr[ i ].second ], money );
			money -= buy;
			cnt += buy;
		}
	}
	money += mid - arr[ pos ].first;
	return ( money >= ( sum - cnt ) * 2 );
}

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

	cin >> n >> m;
	for( int i = 1; i <= n; ++i )
	{
		cin >> order[ i ];
		sum += order[ i ];
	}
	for( int i = 1; i <= m; ++i )
	{
		cin >> arr[ i ].first >> arr[ i ].second;
	}
	sort( arr.begin() + 1, arr.begin() + m + 1 );
	low = 1;
	high = sum * 2;
	while( low <= high )
	{
		mid = ( low + high ) >> 1;
		if( solve() )
		{
			ans = min( ans, mid );
			high = mid - 1;
		}
		else
		{
			low = mid + 1;
		}
	}
	cout << ans << "\n";
	return 0;
}

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<set>
#include<map>
#include<iterator>
#include<stack>
#include<queue>
#include<utility>
#include<functional>
#include<bitset>
#include<numeric>
#include<cstring>
#include<tuple>
using namespace std;

int n, m, sum = 0, low, mid, high, ans = 1e9;
vector< int > order( 2e5 + 5 );
vector< pair< int, int > > arr( 2e5 + 5 );

bool solve( void )
{
	int cnt = 0, money = 0, buy, pos;
	vector< int > last( 2e5 + 5, 0 );
	pos = upper_bound( arr.begin() + 1, arr.begin() + m + 1, make_pair( mid, 200005 ) ) - arr.begin() - 1;
	for( int i = 1; i <= pos; ++i )
	{
		last[ arr[ i ].second ] = i;
	}
	for( int i = 1; i <= pos; ++i )
	{
		money += arr[ i ].first - arr[ i - 1 ].first;
		if( last[ arr[ i ].second ] == i )
		{
			buy = min( order[ arr[ i ].second ], money );
			money -= buy;
			cnt += buy;
		}
	}
	money += mid - arr[ pos ].first;
	return ( money >= ( sum - cnt ) * 2 );
}

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

	cin >> n >> m;
	for( int i = 1; i <= n; ++i )
	{
		cin >> order[ i ];
		sum += order[ i ];
	}
	for( int i = 1; i <= m; ++i )
	{
		cin >> arr[ i ].first >> arr[ i ].second;
	}
	sort( arr.begin() + 1, arr.begin() + m + 1 );
	low = 1;
	high = sum * 2;
	while( low <= high )
	{
		mid = ( low + high ) >> 1;
		if( solve() )
		{
			ans = min( ans, mid );
			high = mid - 1;
		}
		else
		{
			low = mid + 1;
		}
	}
	cout << ans << "\n";
	return 0;
}

/* Author : bhavye9499 - Bhavye Anand Gupta */

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

typedef long long ll;
typedef long double ld;

#define endl "\n"
#define pb emplace_back
#define fi first
#define se second
#define mp make_pair
#define pii pair<ll,ll>
#define max_heap priority_queue<ll>
#define min_heap priority_queue<ll, vector<ll>, greater<ll> >
#define showArr(A,a,n) {for(int i = a; i < a + n; i++) cout << A[i] << " "; cout << endl;}
#define showPair(A,a,n) {for(int i = a; i < a + n; i++) cout << A[i].fi << " " << A[i].se << endl;}

const ll MOD = 1e9 + 7;
const ll MAX = 2e5 + 5;
ll n, m;
vector<ll> A(MAX);
vector<pii> B(MAX);

// bool fun(ll aday) {
// 	ll last[n];
// 	memset(last, -1, sizeof(n));
// 	for(int i = 0; i < m; i++) {
// 		if(B[i].fi <= aday) {
// 			last[B[i].se] = max(last[B[i].se], B[i].fi);
// 		}
// 	}
// 	vector<ll> ldtypes[MAX];
// 	for(int i = 0; i < n; i++) {
// 		if(last[i] != -1) {
// 			ldtypes[last[i]].pb(i);
// 		}
// 	}
// 	vector<ll> req(n);
// 	for(int i = 0; i < n; i++) {
// 		req[i] = A[i];
// 	}
// 	ll money = 0;
// 	for(int i = 0; i <= aday; i++) {
// 		money++;
// 		if(i > 200000) {
// 			continue;
// 		}
// 		for(ll x : ldtypes[i]) {
// 			if(req[x] <= money) {
// 				money -= req[x];
// 				req[x] = 0;
// 			}
// 			else {
// 				req[x] -= money;
// 				money = 0;
// 				break;
// 			}
// 		}
// 	}
// 	ll left = accumulate(req.begin(), req.end(), 0);
// 	return (2 * left <= money);
// }

bool can(ll day) {
	vector<ll> lst(n, -1);
	for (ll i = 0; i < m; ++i) {
		if (B[i].first <= day) {
			lst[B[i].second] = max(lst[B[i].second], B[i].first);
		}
	}
	vector<vector<ll>> off(200001);
	for (ll i = 0; i < n; ++i) {
		if (lst[i] != -1) {
			off[lst[i]].push_back(i);
		}
	}
	vector<ll> need(n);
	for(ll i = 0; i < n; i++) {
		need[i] = A[i];
	}
	ll cur_money = 0;
	for (ll i = 0; i <= day; ++i) {
		++cur_money;
		if (i > 200000) continue;
		for (auto it : off[i]) {
			if (cur_money >= need[it]) {
				cur_money -= need[it];
				need[it] = 0;
			} else {
				need[it] -= cur_money;
				cur_money = 0;
				break;
			}
		}
	}
	return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> m;
	for(int i = 0; i < n; i++) {
		cin >> A[i];
	}
	for(int i = 0; i < m; i++) {
		cin >> B[i].fi >> B[i].se;
		B[i].fi--;
		B[i].se--;
	}

	// sort(B.begin(), B.end());
	ll low = 0, high = 400000;
	while(high - low > 1) {
		ll mid = (high + low) / 2;
		if(can(mid)) {
			high = mid;
		}
		else {
			low = mid;
		}
	}

	for(int i = low; i <= high; i++) {
		if(can(i)) {
			cout << i + 1 << endl;
			return 0;
		}
	}
	// cout << ((can(low)) ? low + 1 : high + 1) << endl;

}

#include<bits/stdc++.h>
#include<string>
#define ll long long
#define lld long double
#define llu unsigned long long int
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define gll(a,n) for(ll i=0;i<n;i++) cin>>a[i];
#define mod 1000000007
#define mod1 998244353
#define pi 3.1415926535897
using namespace std;
ll n,m;
ll a[200001];
pair<ll, ll> b[200001];
ll fun(ll x)
{
    ll i;
    ll day=b[0].fir,c[n+1],sum=0,used=0;
    for(i=1;i<=n;i++)
        c[i]=a[i-1],sum+=a[i-1];
    for(i=0;i<m;i++)
    {
        //cout<<"Sorted: "<<b[i].fir<<" "<<b[i].sec<<endl;
        ll val=b[i].fir;
        if(val>x)
            continue;
        day=min(day,val);
        ll type=b[i].sec;
        if(c[type]>0)
        {
            ll temp=min(c[type],day);
            c[type]-=temp;
            day-=temp;
            sum-=temp;
            used+=temp;
        }
        if(day==0)
            break;
    }
    ll tot=x-used;
    //cout<<"sum: "<<sum<<" tot: "<<tot<<endl;
    if(2*sum<=tot)
        return 1;
    return 0;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //freopen("B-small-attempt0.in", "r", stdin);freopen("output.txt", "w", stdout);
    //std::cout << std::setprecision(9);
    //std::cout << std::fixed;
    ll i,sum=0;
    cin>>n>>m;
    gll(a,n);
    for(i=0;i<n;i++)
        sum+=a[i];
    for(i=0;i<m;i++)
        cin>>b[i].fir>>b[i].sec;
    sort(b, b+m);
    reverse(b, b+m);
    ll l=1,r=2*sum,ans=-1;
    while(l<=r)
    {
        ll m=l+(r-l)/2;
        if(fun(m)==1)
        {
            ans=m;
            r=m-1;
        }
        else
            l=m+1;
    }
    cout<<ans;
}

/// Code by Leonardo16
///   “It is not the strength of the body, but the strength of the spirit.”   —  J.R.R. Tolkien
#include<bits/stdc++.h>
using namespace std;
//#pragma GCC optimize("Ofast")
/// Macros
#define int long long
#define ll long long
#define sz size
#define ull unsigned long long
#define ld long double
#define vi vector<int>
#define ii pair<int,int>
#define vii vector<ii>
#define fst first
#define scd second
#define pb push_back
#define fl '\n'
#define el endl
#define all(x) x.begin() , x.end()
#define rall(x) x.rbegin() , x.rend()
/// Functions
#define db(x) cerr << #x << ": " << (x) << '\n';
#define random() __builtin_ia32_rdtsc()
#define lg2(x) 31-__builtin_clz(x)
#define lg2ll(x) 63-__builtin_clzll(x)
#define pi acos(-1)
#define YN(x) cout<<((x)?("YES"):("NO"))<<fl;
#define yn(x) cout<<((x)?("Yes"):("No"))<<fl;
/// Red-Black Tree Template
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
//typedef tree < long long ,  null_type ,  less<long long> ,  rb_tree_tag ,  tree_order_statistics_node_update > ordered_set;
//#define less_than(n) order_of_key(n)
//#define en_pos(n) find_by_order(n)
/// Prime numbers  173,179,311,331,737,1009,2011,2027,3079,4001,100003
///===================================================================
int n,m;
vi cnt;
vii bono;

bool can(int d){
    vi rem;
    for(int i=0;i<=n;i++){
        rem.pb(cnt[i]);
    }

    vii desc;
    for(int i=0;i<m;i++){
        desc.pb(bono[i]);
    }

    int sum=0;
    int prev=d;
    int gast=0;
    for(int i=m-1;i>=0;i--){
        ii x=desc[i];
        if(x.fst>d){
            continue;
        }
        int dinero=min(prev-gast,x.fst);
        int tipo=x.scd;
        int togast=min(rem[tipo],dinero);
        rem[tipo]-=togast;
        sum+=togast;
        gast=togast;
        prev=dinero;
    }
    for(int i=1;i<=n;i++){
        sum+=2*rem[i];
    }

    return sum<=d;
}

main(){
    ios_base::sync_with_stdio(0);cin.tie(0);
    cnt.pb(0);
    cin>>n>>m;
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        cnt.pb(x);
    }

    for(int i=0;i<m;i++){
        ii x;
        cin>>x.fst>>x.scd;
        bono.pb(x);
    }
    sort(all(bono));

    int wr=0;
    for(int i=20;i>=0;i--){
//        cout<<wr<<el;
        if( wr+(1<<i)<1e6 && !can(wr+(1<<i)) ){
            wr+=(1<<i);
        }
    }
    cout<<wr+1;

return 0;}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;

#define scan(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define all(a) a.begin(),a.end()
#define println printf("\n");
#define readln(x) getline(cin,x);
#define pb push_back
#define endl "\n"
#define INT_INF 0x3f3f3f3f
#define LL_INF 0x3f3f3f3f3f3f3f3f
#define MOD 1000000007
#define MOD2 1494318097
#define SEED 131
#define mp make_pair
#define fastio cin.tie(0); cin.sync_with_stdio(0);

#define MAXN 200005

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
typedef unordered_map<int,int> umii;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef pair<int,pii> triple;
typedef int8_t byte;

mt19937 g1(time(0));

int randint(int a, int b){return uniform_int_distribution<int>(a, b)(g1);}
ll randlong(ll a,ll b){return uniform_int_distribution<long long>(a, b)(g1);}

ll gcd(ll a, ll b){return b == 0 ? a : gcd(b, a % b);}
ll lcm(ll a, ll b){return a*b/gcd(a,b);}
ll fpow(ll  b, ll exp, ll mod){if(exp == 0) return 1;ll t = fpow(b,exp/2,mod);if(exp&1) return t*t%mod*b%mod;return t*t%mod;}
ll divmod(ll i, ll j, ll mod){i%=mod,j%=mod;return i*fpow(j,mod-2,mod)%mod;}

int num_tran,num_offer,req[MAXN],tmp[MAXN],lst[MAXN];
pii offers[MAXN];

inline bool works(int day){
	for(int i=1; i<=num_tran; i++){
		tmp[i] = req[i];
		lst[i] = -1;
	}
	for(int i=1; i<=num_offer; i++){
		if(offers[i].first <= day)
			lst[offers[i].second] = offers[i].first;
	}
	vector<pii> v;
	for(int i=1; i<=num_tran; i++)
		if(lst[i] != -1)
			v.pb(mp(lst[i],i));
	sort(all(v));
	int ptr = 1;
	for(int i=0; i<v.size(); i++){
		int idx = v[i].second;
		while(tmp[idx] && ptr <= v[i].first){
			tmp[idx]--;
			ptr++;
		}
	}
	vector<int> rem;
	for(int i=1; i<=num_tran; i++) if(tmp[i]) rem.pb(i);
	int money = 0;
	for(int i=ptr; i<=day; i++){
		money++;
		if(money >= 2 && rem.size()){
			tmp[rem.back()]--, money-=2;
			if(tmp[rem.back()] == 0) rem.pop_back();
		}
	}
	if(rem.size()) return false;
	return true;
}

int main(){
	scanf("%d %d",&num_tran,&num_offer);
	for(int i=1; i<=num_tran; i++)
		scanf(" %d",&req[i]);
	for(int i=1; i<=num_offer; i++)
		scanf(" %d %d",&offers[i].first,&offers[i].second);
	sort(offers+1,offers+num_offer+1);
	int low = 0, high = 1e6, ans = 1e6;
	while(low <= high){
		int mid = (low+high)/2;
		if(works(mid)){
			ans = mid;
			high = mid-1;
		}else low = mid+1;
	}
	printf("%d\n",ans);
}
/*
4 7
23 78 12 46
87 1
100 1
213 2
12 2
76 2
41 3
321 3
ans=213

2 2
2 3
2 1
5 2
ans=5
 */

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> pii;

int n, m;
int arr[200200];

int main() {
    scanf("%d %d", &n, &m);

    int total_buy = 0;
    for (int i = 1; i <= n; i++){
        scanf("%d", &arr[i]);
        total_buy += arr[i];
    }

    pii promo[200200];

    for (int i = 0; i < m; i++){
        int d, t;
        scanf("%d %d", &d, &t);
        promo[i].first = d;
        promo[i].second = t;
    }

    int l = 0, r = 400001;

    while (l < r) {
        int mid = (l + r) / 2;

        int last_promo[200200];
        memset(last_promo, 0, sizeof last_promo);
        for (int i = 0; i < m; i++) {
            int d = promo[i].first, t = promo[i].second;
            if (promo[i].first <= mid)
                last_promo[t] = max(last_promo[t], d);
        }

        int must_buy[200200];
        memset(must_buy, 0, sizeof must_buy);
        for (int i = 1; i <= n; i++) {
            must_buy[last_promo[i]] += arr[i];
        }

        int money = 0;
        int bought = 0;
        for (int i = 1; i <= mid; i++) {
            money++;
            if (i > 200000) continue;
            if (money > must_buy[i]) {
                bought += must_buy[i];
                money -= must_buy[i];
            } else {
                bought += money;
                money = 0;
            }
        }
        if (money >= 2 * (total_buy - bought)) {
            r = mid;
        } else {
            l = mid + 1;
        }
    }

    printf("%d\n", l);

}

#include <iostream>
#include <algorithm>
#include <map>
#include <set>

const int maxn = 2e5+7;

int n, m, k[maxn], kk[maxn];
std::set<int> dt[maxn];
int sumk = 0;

bool check(int x) {
	for (int i = 0; i < maxn; i++) {
		kk[i] = k[i];
	}
	int now = 0;
	int cur = x;
	for (int i = x; i > 0; i--) {
		cur = std::min(cur, i);
		for (auto it: dt[i]) {
			if (kk[it] > 0) {
				int pur = std::min(kk[it], cur);
//				std::cout << "day " << i << " spent " << pur << " on " << it << "\n";
				cur -= pur;
				kk[it] -= pur;
				now += pur;
			}
		}
	}
	if (x-now >= (sumk-now)*2) {
//		std::cout << cur << " " << now << ' ';
//		std::cout << x << " yes\n";
		return 1;
	}
//	std::cout << x << " no\n";
	return 0;
}

int main(int argc, char *argv[]) {
	std::cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		std::cin >> k[i];
		sumk += k[i];
	}
	int dd, tt;
	for (int i = 1; i <= m; i++) {
		std::cin >> dd >> tt;
		dt[dd].insert(tt);
	}
	int l = sumk, r = sumk*2, mid;
	while (l <= r) {
		mid = (l+r)/2;
		if (check(mid)) {
			r = mid-1;
		} else {
			l = mid+1;
		}
	}
	std::cout << l << '\n';
}

#include <bits/stdc++.h>

using namespace std;

int n, m;
vector<int> k;
vector<pair<int, int>> q(200001);

bool can(int day) {
	vector<int> lst(n, -1);
	for (int i = 0; i < m; ++i) {
		if (q[i].first <= day) {
			lst[q[i].second] = max(lst[q[i].second], q[i].first);
		}
	}
	vector<vector<int>> off(200001);
	for (int i = 0; i < n; ++i) {
		if (lst[i] != -1) {
			off[lst[i]].push_back(i);
		}
	}
	vector<int> need = k;
	int cur_money = 0;
	for (int i = 0; i <= day; ++i) {
		++cur_money;
		if (i > 200000) continue;
		for (auto it : off[i]) {
			if (cur_money >= need[it]) {
				cur_money -= need[it];
				need[it] = 0;
			} else {
				need[it] -= cur_money;
				cur_money = 0;
				break;
			}
		}
	}
	return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}

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

	cin >> n >> m;
	k = vector<int>(n);
	for (int i = 0; i < n; ++i) {
		cin >> k[i];
	}
	for (int i = 0; i < m; ++i) {
		cin >> q[i].first >> q[i].second;
		--q[i].first;
		--q[i].second;
	}

	int l = 0, r = 400000;
	while (r - l > 1) {
		int mid = (l + r) >> 1;
		if (can(mid)) r = mid;
		else l = mid;
	}

	for (int i = l; i <= r; ++i) {
		if (can(i)) {
			cout << i + 1 << endl;
			return 0;
		}
	}

	assert(false);

	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=2e5+9;
int n,m,k[N];
#define P pair<int,int>
P a[N];
int tmp[N];
bool check(int x){
    memcpy(tmp,k,sizeof(k));
    int xx=x;
    int used=0,now=x;
    for(int i=m;i>=1;i--){
        if(a[i].first>xx)continue;
        now=min(now,a[i].first);
        if(tmp[a[i].second]){
            used=min(now,tmp[a[i].second]);
            tmp[a[i].second]-=used;
            x-=used;
            now-=used;
        }
    }
    int sum=0;
    for(int i=1;i<=n;i++)sum+=tmp[i];
    return x>=2*sum;
}
int main(){
   // freopen("tt.in","r",stdin),freopen("tt.out","w",stdout);
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>k[i];
    for(int i=1;i<=m;i++)cin>>a[i].first>>a[i].second;
    sort(a+1,a+m+1);
    int l=0,r=N*2,mid,ans;
    while(l<=r){
        mid=(l+r)>>1;
        if(check(mid))ans=mid,r=mid-1;
        else l=mid+1;
    }
    cout<<ans<<endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
int tot;
int a[maxn];
int b[maxn];
int n,m;
vector<int>v[maxn];
bool check(int mid)
{
	int sum = 0;
	int m = mid;
	memset(b,0,sizeof(b));
	for(int i=mid-1;i>=0;i--)
	{
		if(m > i+1)m--;
		int len = v[i].size();
		for(int j=0;j<len;j++)
		{
			int x = v[i][j];
			int diff = min(a[x]-b[x],m);
			m-=diff;
			sum+=diff;
			b[x]+=diff;
		}
	}
	if(tot*2 > mid + sum)return false;
	return true;
}
int main()
{
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		tot+=a[i];
	}
	while(m--)
	{
		int a,b;
		cin>>a>>b;
		v[--a].push_back(--b);
	}
	int l = tot;
	int r = 2*tot;
	while(l < r)
	{
		int mid = (l+r) >>1;
		if(check(mid))r = mid;
		else l = mid+1;
	}
	cout<<l<<endl;
}

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

const int maxn= 2e5+2;
long long n, m, v[maxn], v1[maxn];

vector<long long>G[maxn];

bool solve(long long x)
{
    vector<pair<long long, long long> >R;
    memcpy(v1, v, sizeof v);
    for(int i=1; i<=n; i++)
    {
        if(G[i].size()!=0&&G[i][0]<=x)
        {
            int st=0, res=0, dr=G[i].size()-1;
            while(st<=dr)
            {
                int mid=(st+dr)/2;
                if(G[i][mid]<=x)
                {
                    res=mid;
                    st=mid+1;
                }
                else
                {
                    dr=mid-1;
                }
            }
            //reduc[i]=G[i][res];
            R.push_back({G[i][res], i});
        }
    }
    sort(R.begin(),R.end());
    long long ruble=0, prev=0;
    for(auto it:R)
    {
        ruble=ruble+it.first-prev;
        prev=it.first;
        long long cate = min(v1[it.second], ruble);
        ruble=ruble-cate;
        v1[it.second]=v1[it.second]-cate;
    }
    ruble=ruble+x-prev;
    long long total=0;
    for(int i=1; i<=n; i++)
    {
        total=total+v1[i];
    }
    if(2*total<=ruble)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    int x, y;
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        cin>>v[i];
    }
    for(int i=1; i<=m; i++)
    {
        cin>>x>>y;
        G[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
    {
        sort(G[i].begin(),G[i].end());
    }
    long long st=1, dr=2000, res=2000;
    while(st<=dr)
    {
        long long mid=(st+dr)/2;
        if(solve(mid))
        {
            res=mid;
            dr=mid-1;
        }
        else
        {
            st=mid+1;
        }
    }
    cout<<res;
    return 0;
}

#include<bits/stdc++.h>
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long INT;
typedef pair<int,int> pii;
#define NN 200200
int a[NN],fl[NN],b[NN],c[NN],mx[NN];
pii p[NN];
vector <int> vec[NN],adj[NN];
int main(){
#ifndef ONLINE_JUDGE
	freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
#endif
	int n,m,s=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++) scanf("%d",a+i),s+=a[i];
	for(int i=1;i<=m;i++) scanf("%d%d",&p[i].y,&p[i].x);
	sort(p+1,p+m+1);
	for(int i=1;i<=m;i++) vec[p[i].x].pb(p[i].y);
	int st=0,ed=2*s;
	while(st+1<ed){
		int mid=st+ed>>1;
		for(int i=1;i<=n;i++){
			int r=upper_bound(vec[i].begin(),vec[i].end(),mid)-vec[i].begin();
			if(r>0) adj[vec[i][r-1]].pb(i);
			b[i]=a[i];
		}
		int mo=0;
		for(int i=1;i<=mid;i++){
			mo++;
			if(i<=200000) for(int v:adj[i]){
				if(mo>a[v]) mo-=b[v],b[v]=0;
				else {b[v]-=mo;mo=0;break;}
			}
		}
		int tt=0;
		for(int i=1;i<=n;i++) tt+=b[i];
		mo-=tt*2;
		if(mo>=0) ed=mid;
		else st=mid;
		for(int i=1;i<=200000;i++) adj[i].clear();
	}
	cout<<ed<<endl;
	return 0;
}

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

using ll = long long;
#define int ll
using ld = long double;
using db = double;
using str = string; // yay python!

using pi = pair<int,int>;
using pl = pair<ll,ll>;
using pd = pair<db,db>;

using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;

#define tcT template<class T
#define tcTU tcT, class U
// ^ lol this makes everything look weird but I'll try it
tcT> using V = vector<T>;
tcT, size_t SZ> using AR = array<T,SZ>;
tcT> using PR = pair<T,T>;

// pairs
#define mp make_pair
#define f first
#define s second

// vectors
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

// loops
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18; // not too close to LLONG_MAX
const ld PI = acos((ld)-1);
const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; // for every grid problem!!
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;

// helper funcs
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down

tcT> bool ckmin(T& a, const T& b) {
    return b < a ? a = b, 1 : 0; } // set a = min(a,b)
tcT> bool ckmax(T& a, const T& b) {
    return a < b ? a = b, 1 : 0; }

tcTU> T fstTrue(T lo, T hi, U f) {
    hi ++; assert(lo <= hi); // assuming f is increasing
    while (lo < hi) { // find first index such that f is true
        T mid = lo+(hi-lo)/2;
        f(mid) ? hi = mid : lo = mid+1;
    }
    return lo;
}
tcTU> T lstTrue(T lo, T hi, U f) {
    lo --; assert(lo <= hi); // assuming f is decreasing
    while (lo < hi) { // find first index such that f is true
        T mid = lo+(hi-lo+1)/2;
        f(mid) ? lo = mid : hi = mid-1;
    }
    return lo;
}
tcT> void remDup(vector<T>& v) { // sort and remove duplicates
    sort(all(v)); v.erase(unique(all(v)),end(v)); }
tcTU> void erase(T& t, const U& u) { // don't erase
    auto it = t.find(u); assert(it != end(t));
    t.erase(u); } // element that doesn't exist from (multi)set

// INPUT
#define tcTUU tcT, class ...U
tcT> void re(complex<T>& c);
tcTU> void re(pair<T,U>& p);
tcT> void re(vector<T>& v);
tcT, size_t SZ> void re(AR<T,SZ>& a);

tcT> void re(T& x) { cin >> x; }
void re(db& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
tcTUU> void re(T& t, U&... u) { re(t); re(u...); }

tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; }
tcTU> void re(pair<T,U>& p) { re(p.f,p.s); }
tcT> void re(vector<T>& x) { trav(a,x) re(a); }
tcT, size_t SZ> void re(AR<T,SZ>& x) { trav(a,x) re(a); }

// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) {
    #ifdef LOCAL
        return b ? "true" : "false";
    #else
        return ts((int)b);
    #endif
}
tcT> str ts(complex<T> c) {
    stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
    str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
    res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
    str res = ""; F0R(i,SZ) res += char('0'+b[i]);
    return res; }
tcTU> str ts(pair<T,U> p);
tcT> str ts(T v) { // containers with begin(), end()
    #ifdef LOCAL
        bool fst = 1; str res = "{";
        for (const auto& x: v) {
            if (!fst) res += ", ";
            fst = 0; res += ts(x);
        }
        res += "}"; return res;
    #else
        bool fst = 1; str res = "";
        for (const auto& x: v) {
            if (!fst) res += " ";
            fst = 0; res += ts(x);
        }
        return res;

    #endif
}
tcTU> str ts(pair<T,U> p) {
    #ifdef LOCAL
        return "("+ts(p.f)+", "+ts(p.s)+")";
    #else
        return ts(p.f)+" "+ts(p.s);
    #endif
}

// OUTPUT
tcT> void pr(T x) { cout << ts(x); }
tcTUU> void pr(const T& t, const U&... u) {
    pr(t); pr(u...); }
void ps() { pr("\n"); } // print w/ spaces
tcTUU> void ps(const T& t, const U&... u) {
    pr(t); if (sizeof...(u)) pr(" "); ps(u...); }

// DEBUG
void DBG() { cerr << "]" << endl; }
tcTUU> void DBG(const T& t, const U&... u) {
    cerr << ts(t); if (sizeof...(u)) cerr << ", ";
    DBG(u...); }
#ifdef LOCAL // compile with -DLOCAL, chk -> fake assert
    #define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
    #define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \
         << __FUNCTION__  << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0);
#else
    #define dbg(...) 0
    #define chk(...) 0
#endif

// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { cin.tie(0)->sync_with_stdio(0); }
void setIO(str s = "") {
    unsyncIO();
    cin.exceptions(cin.failbit);
    // throws exception when do smth illegal
    // ex. try to read letter into int
    if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
}

namespace std {

template<class Fun>
class y_combinator_result {
	Fun fun_;
public:
	template<class T>
	explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}

	template<class ...Args>
	decltype(auto) operator()(Args &&...args) {
		return fun_(std::ref(*this), std::forward<Args>(args)...);
	}
};

template<class Fun>
decltype(auto) y_combinator(Fun &&fun) {
	return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}

} // namespace std

const int MM = 3e5+5;
int n,m,k[MM],mx[MM],tmp[MM]; vector<pi> de;
vector<int> d[MM];
bool check(int x){
	for(int i = 1; i <= x; i++) d[i].clear();
	memcpy(tmp,k,sizeof k); memset(mx,0,sizeof mx);
	for(int i = 0; i < m; i++){
		if(de[i].f > x) continue;
		mx[de[i].s] = max(mx[de[i].s],de[i].f);
	}

	for(int i = 1; i <= n; i++){
		if(mx[i] == 0) continue;
		d[mx[i]].eb(i);
	}

	int mon = 0;
	for(int i = 1; i <= x; i++){
		mon++;
		for(int y : d[i]){
			while(k[y]){
				k[y]--; mon--;
				if(mon <= 0) break;
			}
			if(mon <= 0) break;
		}
	}

	int cnt = accumulate(k+1,k+1+n,0);
	mon -= 2*cnt;
	memcpy(k,tmp,sizeof tmp);
	return mon >= 0;
}

signed main(){
    setIO();
	cin >> n >> m;
	for(int i = 1; i <= n; i++) cin >> k[i];
	for(int i = 0; i < m; i++){
		int x,y; cin >> x >> y; de.eb(x,y);
	}
	//check(8);
	int lo = 1, hi = MM-5;
	while(lo < hi){
		int mid = (lo+hi)/2;
		if(check(mid)) hi = mid;
		else lo = mid+1;
	}
	assert(check(lo));
	cout << lo << "\n";

    // you should actually read the stuff at the bottom
}

/* stuff you should look for
    * int overflow, array bounds
    * special cases (n=1?)
    * do smth instead of nothing and stay organized
    * WRITE STUFF DOWN
    * DON'T GET STUCK ON ONE APPROACH
*/

#include<bits/stdc++.h>

#define LL long long
#define fi first
#define se second
#define mp make_pair
#define pb push_back

using namespace std;

LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
const int N = 5e5 +11;
int n,m,a[N];
struct uzi
{
	int t,d;
}p[N];
int b[N],sum,c[N];
vector<int>v[N];
int C(int x){
	sum=0;int now=0;
	for(int i=1;i<=n;i++)b[i]=a[i],sum+=a[i],c[i]=0,v[i].clear();
	for(int i=1;i<=m;i++)if(p[i].t<=x)c[p[i].d]=max(c[p[i].d],p[i].t);
	for(int i=1;i<=m;i++)if(p[i].t<=x&&c[p[i].d]==p[i].t)v[p[i].t].pb(p[i].d);
	for(int i=1;i<=x;i++){
		now++;
		for(auto k:v[i]){
			int d=min(now,b[k]);
			now-=d;
			b[k]-=d;
			sum-=d;
		}
	}
	return now>=2*sum;
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n>>m;
	for(int i=1;i<=n;i++)cin>>a[i];
	for(int i=1;i<=m;i++)cin>>p[i].t>>p[i].d;
	int l=0,r=400000+4,ans=0;
	while(l<=r){
		int mid=l+r>>1;
		if(C(mid))ans=mid,r=mid-1;
		else l=mid+1;
	}
	cout<<ans<<endl;
	return 0;
}

//============================================================================
// Name        : f1
// Date        : Fri May 17 20:57:01 CST 2019
// Author      : landcold7
// Description : Actions speak louder more than words
//============================================================================
#include <bits/stdc++.h>
using namespace std;

#define x first
#define y second
#define pb push_back
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
template<typename T> void output(T t) { cout << t << "\n"; }
template<typename T, typename U, typename... Args>
void output(T t, U u, Args... args) { cout << t << " "; output(u, args...); }

#ifndef _has_trace
#define trace(...)
#define dbstream ostream
#endif
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;

const int maxn = 1e3 + 7;

void solve() {
  int n, m;
  cin >> n >> m;
  vi a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
  }
  vector<pii> b(m);
  for (int i = 0; i < m; ++i) {
    cin >> b[i].x >> b[i].y;
    --b[i].x, --b[i].y;
  }
  auto check = [&](int day) {
    vi sale(maxn, -1);
    for (int i = 0; i < m; ++i) {
      int d = b[i].x, t = b[i].y;
      if (d <= day) {
      // The last day in which the `t`th good is for sale.
        sale[t] = max(sale[t], d);
      }
    }
    vector<vi> goods(maxn);
    for (int i = 0; i < n; ++i) {
      if (sale[i] != -1) {
      // Compute all the goods will be on sale for a specific day.
        goods[sale[i]].pb(i);
      }
    }
    vi need = a;
    int money = 0;
    for (int i = 0; i <= day; ++i) {
      money++;
      if (i >= maxn) {
        continue;
      }
      for (auto it : goods[i]) {
        if (money >= need[it]) {
          money -= need[it];
          need[it] = 0;
        } else {
          need[it] -= money;
          money = 0;
          break;
        }
      }
    }
    return accumulate(all(need), 0) * 2 <= money;
  };
  int lo = -1, hi = 4 * 1e5 + 7;
  while (hi - lo > 1) {
    int mid = lo + (hi - lo) / 2;
    if (check(mid)) {
      hi = mid;
    } else {
      lo = mid;
    }
  }
  output(hi + 1);
}

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

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
#define PI 3.14159265358979323846
#define int ll
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 4e5+10;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
    return x*f;
}
int a[maxn], ans;
std::vector<int> v[maxn];
int b[maxn];
int n, m;
bool check(int mid){
    int num = ans;
    for(int i = 1; i <= n; i++) b[i] = a[i];
    // *b = *a;
     /*rep(i,1,n) printf("%d ", b[i]);printf("\n");
     rep(i,1,n) printf("%d ", a[i]);printf("\n");*/
    int cnt = 0, left=mid;
    for(int i = mid; i >= 1 && left; i--){
        for(auto xx : v[i]){
            if(!b[xx]) continue;
            int tmp = min(b[xx], left);
            b[xx] -= tmp;
            left -= tmp;
            num -= tmp;
        }
        if(left==i){
            cnt++;
            left = i-1;
        }
    }
    return cnt>=num*2;
}
signed main(){
    n=read(), m=read();
    ans = 0;
    for(int i = 1; i <= n; i++) a[i]=read(), ans+=a[i];
    for(int i = 1; i <= m; i++) {int d=read(), t=read(); v[d].push_back(t);}
    int l = ans, r = ans*2;
    int res=0;
    while(l<=r){
        int mid = (l+r)/2;
        if(check(mid)){
            res = mid;
            r = mid-1;
        }else l = mid+1;
    }
    printf("%lld\n", res);
    return 0;
}

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pll;
typedef pair<int, int>pii;
typedef pair<double, double>pdd;

const ll maxx = 790;
const ll maxn = 500000+7;
const ll mod = 998244353;
const ll maxs = 500000 + 7;
const ll maxm = 400000 + 7;
const ll maxk = 1008 + 7;
const ll maxw = 100 + 7;
const ll maxh = 100 + 7;
const double pi = 3.1415926;
const ll ten = 10;
const ll ooi = 1000000;
const ll ool = 1e18 + 7;
const ldb eps = 1e-8;
const int apsz = 26;

//#define __TREE
#ifdef __TREE
	#define lc(xx) (xx<<1)
	#define rc(xx) ((xx<<1)|1)
#endif

#define vi vector<int>
#define vl vector<ll>
#define _for(i,a,b) for(ll i=(a);i<(b);i++)
#define _rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define _dep(i,a,b) for(ll i=(a);i>=(b);i--)
#define msz(ss) memset(ss,0,sizeof(ss))
#define msllz(ss) memset(ss,(ll)0,sizeof(ss))
#define mszull(ss) memset(ss,(ull)0,sizeof(ss))
#define msllneg(ss) memset(ss,(ll)-1,sizeof(ss))
#define msitt(xx) memset(xx,1,sizeof(xx))
#define IO ios::sync_with_stdio(false);cout.tie(0);cin.tie(0)
#define init_int_dp(dp) memset(dp,-1,sizeof(dp))
#define init_ll_dp(dp) memset(dp,-1ll,sizeof(dp))
#define all(x) x.begin(),x.end()
#define pb push_back
#define sz size
#define fr first
#define sc second
#define mp make_pair

int n,m;
int all;
vi nd;
vector<int> ds[maxn];
void init()
{
	cin>>n>>m;
	_for(i,0,n)
	{
		int tp;
		cin>>tp;
		nd.pb(tp),all+=tp;
	}
	_for(i,0,m)
	{
		int u,v;
		cin>>u>>v,v--;
		ds[u].pb(v);
	}
}

int ju(int x)
{
	vector<int> td(n,0);
	int yu1=x;
	int has=0;
	int cost=0;
	for(int i=x;i>=1;i--)
	{
		if(i<yu1)
			yu1=i;
		for(auto x:ds[i])
		{
			int de = min(yu1,nd[x]-td[x]);
			td[x]+=de;
			has+=de;
			cost+=de;
			yu1-=de;
		}
	}
	int wgr = all-has;
	if(wgr*2<=x-has)
		return 1;
	return 0;
}

void solve()
{
	int L = 0;
	int R = all*2;
	while(L<R)
	{
		int mid = R-(R-L+1)/2;
		if(ju(mid))
			R = mid;
		else
			L = mid+1;
	}
	cout<<R<<endl;
}

int main(void)
{
#ifdef OJ
	freopen("buffcraft.in", "r", stdin);
	freopen("a.txt", "w", stdout);
#endif
#ifdef TEST
	freopen("a.txt", "w", stdout);
#endif
	IO;
	init();
	solve();
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
template<class T> ostream& operator<<(ostream &os, vector<T> V) {
os << "[ "; for(auto v : V) os << v << " "; return os << "]";}
template<class L, class R> ostream& operator<<(ostream &os, pair<L,R> P) {
    return os << "(" << P.first << "," << P.second << ")";}

// #define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cout << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...) 1
#endif
typedef long long ll;
typedef double ld;
#define pll pair<ll,ll>
#define pb push_back
#define mp(x, y) make_pair((x), (y))
#define F first
#define S second
#define I insert
#define vll vector<ll>
#define vpll vector<pll>
#define all(x) (x).begin(), (x).end()
#define sz(x) (ll)(x).size()

int n , m , c , d , t , Total;

int req[200007];

map<int , vector<int> > sale;

bool check(int days){

    int temp[n+1];
    for(int i = 0 ;i < n+1 ; i++)
        temp[i] = req[i];

    int curr = days , spent = days;
    int dummy = Total;

    for(int i = days; i >= 1 ; i--){

        curr = min(curr , i);

        if(sale.find(i) != sale.end()){

            for(auto it : sale[i]){
                if(curr > 0  && temp[it] > 0){
                    if(temp[it] <= curr){
                        curr -= temp[it];
                        spent -= temp[it];
                        dummy -= temp[it];
                        temp[it] = 0;
                    }
                    if(temp[it] > curr){
                        spent -= curr;
                        temp[it] -= curr;
                        dummy -= curr;
                        curr = 0;
                    }
                }
            }
        }
    }

    if(2*dummy <= spent)
        return true;
    return false;
}

const ll Mod = 1e9 + 7;
int main(){
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n >> m;
    for(int i = 1 ; i <= n; i++){
        cin >> c;
        Total += c;
        req[i] = c;
    }
    for(int i = 0 ;i < m ; i++){
        cin >> d >> t;
        sale[d].pb(t);
    }

    int left = 1 , right = 1000000;
    int mn = Mod;
    while(left <= right){
        int mid = (left+right)/2;
        if(check(mid)){
            mn = min(mn , mid);
            right = mid-1;
        }
        else
            left = mid+1;
    }
    cout << mn << endl;
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

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

const int maxn =1e5+100;

int n,m,a,b;
ll k[maxn],tmp[maxn]={0};
pii p[maxn];
int vis[maxn];

bool check(ll mid){
	ll my=mid;
	for(int i=1;i<=n;++i){
		tmp[i]=k[i];
		//cout<<tmp[i]<<" ";
		vis[i]=0;
	}
	//cout<<endl;
	// for(int i=1;i<=n;++i){
	// 	cout<<vis[i]<<" ";
	// }
	// cout<<endl;
	for(int i=1;i<=m;++i){
		if(p[i].first>mid) break;
		vis[p[i].second]=max(vis[p[i].second],p[i].first);
	}
	// for(int i=1;i<=n;++i){
	// 	cout<<vis[i]<<" ";
	// }
	// cout<<endl;
	ll earn=0;ll yd=0;
	for(int i=1;i<=m;++i){
		if(p[i].first>mid) break;

		if(vis[p[i].second]>p[i].first) continue;
		earn+=p[i].first-yd;
		yd=p[i].first;
	//	cout<<p[i].first<<" "<<p[i].second<<" "<<earn<<endl;
		if(tmp[p[i].second]&&earn){
			ll mi=min(tmp[p[i].second],earn);
			tmp[p[i].second]-=mi;
			my-=mi;
			earn-=mi;
		}
	}
	//cout<<"end"<<" "<<my<<endl;
	for(int i=1;i<=n;++i){
		//cout<<i<<" "<<tmp[i]<<endl;
		my-=tmp[i]*2;
	}
	//cout<<"end111"<<" "<<my<<endl;
//	cout<<mid<<" "<<my<<endl;
	return my>=0;
}

int main(){

	ios::sync_with_stdio(false);
	cin>>n>>m;
	for(int i=1;i<=n;++i){
		cin>>k[i];
	}
	for(int i=1;i<=m;++i){
		cin>>p[i].first>>p[i].second;
	}
	sort(p+1,p+1+m);
	p[0].first=0;
	//check(214);
	ll ans=8e10;
	ll l=0,r=8e10;
	while(l<=r){
		ll mid=(r+l)/2;
	//	cout<<mid<<endl;
		if(check(mid)){
			r=mid-1;
			ans=mid;
		}else l=mid+1;
	}
	cout<<ans<<endl;
	return 0;
}

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
using namespace std;
const int maxn = 4e5+10;

int read(){
	int x=0,f=1;
	char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=(x<<3)+(x<<1)+c-48;c=getchar();}
	return x*f;
}

int k,m,n,num=2e5;
int sum[maxn],S[maxn];
vector<int> a[maxn];
inline bool check(int mid){
	int last=mid,ans=0;
	for(register int i=1;i<=n;i++)sum[i]=S[i];
	for(register int i=mid;i>=1;i--){
		last=min(last,i);
		for(register int j=0;j<a[i].size();j++){
			int x=a[i][j];
			if(last>=sum[x]){last-=sum[x];ans+=sum[x];sum[x]=0;}
			else {sum[x]-=last;ans+=last;last=0;}
		}
	}
	for(register int i=1;i<=n;i++)ans+=sum[i]*2;
	if(ans<=mid)return true;
	return false;
}

int main(){
	n=read();m=read();
	for(register int i=1;i<=n;i++)S[i]=sum[i]=read();
	for(register int i=1;i<=m;i++){
		int x=read(),y=read();
		a[x].push_back(y);
	}/*
	int last=num,ans=0,summ=0;;
	for(register int i=num;i>=1;i--){
		last=min(last,i);
		for(register int j=0;j<a[i].size();j++){
			int x=a[i][j];
			if(last>=sum[x]){last-=sum[x];ans+=sum[x];sum[x]=0;}
			else {sum[x]-=last;ans+=last;last=0;}
		}
	}
	for(register int i=1;i<=n;i++)ans+=sum[i]*2;
	printf("%d\n",ans-summ);*/
	int l=1,r=num*2,ans;
	while(l<=r){
		int mid=(l+r)>>1;
		if(check(mid)){r=mid-1;ans=mid;}
		else l=mid+1;
	}
	printf("%d\n",ans);
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

int n, m;
vector<int> k;
vector<pair<int, int>> q(1001);

bool can(int day) {
    vector<int> lst(n, -1);
    for (int i = 0; i < m; ++i) {
        if (q[i].first <= day) {
            lst[q[i].second] = max(lst[q[i].second], q[i].first);
        }
    }
    vector<vector<int>> off(1001);
    for (int i = 0; i < n; ++i) {
        if (lst[i] != -1) {
            off[lst[i]].push_back(i);
        }
    }
    vector<int> need = k;
    int cur_money = 0;
    for (int i = 0; i <= day; ++i) {
        ++cur_money;
        if (i > 1000) continue;
        for (auto it : off[i]) {
            if (cur_money >= need[it]) {
                cur_money -= need[it];
                need[it] = 0;
            } else {
                need[it] -= cur_money;
                cur_money = 0;
            }
        }
    }
    return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}

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

    cin >> n >> m;
    k = vector<int>(n);
    for (int i = 0; i < n; ++i) {
        cin >> k[i];
    }
    for (int i = 0; i < m; ++i) {
        cin >> q[i].first >> q[i].second;
        --q[i].first;
        --q[i].second;
    }

    for (int l = 0; l <= 2000; ++l) {
        if (can(l)) {
            cout << l + 1 << endl;
            return 0;
        }
    }

    assert(false);

    return 0;
}

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

#define MAX 200001

#define d first
#define t second

int n,m;
int k[MAX],c[MAX];
pair<int,int> sales[MAX];

bool result(int d){
    int f = m-1;
    for(int i = 0 ; i < m ; i++ ){
        if(sales[i].d > d){
            f = i-1;
            break;
        }
    }
    memcpy(c,k,sizeof(k));
    int w , dth = d;
    for(int i = f ; i >= 0 ; i--){
        dth = min(dth,sales[i].d);
        w = min(dth,c[sales[i].t]);
        d -= w;
        dth -= w;
        c[sales[i].t] -= w;
    }
    for(int i = 1 ; i <= n ; i++ ) d -= 2*c[i];

    return d >= 0;
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i = 1 ; i <= n ; i++ ) scanf("%d",&k[i]);
    for(int i = 0 ; i < m ; i++ ) scanf("%d%d",&sales[i].d , &sales[i].t);
    sort(sales,sales+m);

    int high = INT_MAX , mid , low = 0;
    int ans;
    while(low <= high){
        mid = (high + low) / 2;
        if(result(mid)){
            ans = mid;
            high = mid-1;
        }
        else low = mid+1;
    }
    printf("%d\n",ans);
}

#include <algorithm>
#include <iomanip>
#include <istream>
#include <map>
#include <numeric>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <memory>
using namespace std;
// Powered by caide (code generator, tester, and library code inliner)

class Solution {
public:
	void solve(std::istream& in, std::ostream& out) {
		int n, m;
		in >> n >> m;
		vector<int> cnt(n);
		for(int i=0;i<n;i++)in>>cnt[i];
		vector<vector<int>>sm(n);
		map<int, vector<int>> sm2;

		while(m--)
		{
			int d, t;
			in >> d >> t;
			t--;
			sm[t].push_back(d);
			sm2[d].push_back(t);
		}

		for(auto &p:sm)
		{
			sort(p.begin(), p.end());
			p.erase(unique(p.begin(), p.end()), p.end());
		}

		int l = 0;
		int r = 5000;
		while (r-l>1)
		{
 			int m = (l+r)/2;
			vector<int> s(n, -1);
			for(int i=0;i<n;i++)
			{
				auto it = upper_bound(sm[i].begin(), sm[i].end(), m);
				if (it!=sm[i].begin())
				{
					it--;
					s[i] = *it;
				}
			}

			int rem=0;
			for(int x:cnt)rem+=x;

			vector<int> _cnt=cnt;

			int c=0;
			for(int d=1;d<=m;d++)
			{
				c++;
				auto it = sm2.find(d);
				if (it==sm2.end())continue;

				for(int t:it->second)
				{
					if (s[t]==d)
					{
						int k = min(c, _cnt[t]);

						c-=k;
						_cnt[t]-=k;
						rem-=k;
					}
				}
			}

			if (c>=rem*2)
			{
				r=m;
			} else
			{
				l = m;
			}
		}

		out << r << endl;

	}
};

void solve(std::istream& in, std::ostream& out)
{
    out << std::setprecision(12);
    Solution solution;
    solution.solve(in, out);
}

#include <fstream>
#include <iostream>

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(0);

    istream& in = cin;

    ostream& out = cout;

    solve(in, out);
    return 0;
}

//F1. Microtransactions (easy version)

#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int MAXN = 2e6;
int k[MAXN]; //每一件商品的数量
int k_[MAXN];
vector<int>  Vec[MAXN];

int ans;
	int n,m;
int Ok(int Mid,int ans)
{
	int tag = 0;
	int re = Mid,y = ans;
	for(int i = 1;i <= n;i++)
		k_[i] = k[i];
	for(int i = Mid;i >= 1;i--)
	{
		for(int j = 0;j < Vec[i].size();j++)
			while(re && k_[Vec[i][j]])
			{
				re--;//剩余的钱的数量减1
				k_[Vec[i][j]]--;//这一种物品需要的数量-1
				y--;//总共需要买的物品数量-1
			}
		if(re >= i)
		{
			tag++; //最后多出来的钱的数量
			re--;
		}
	}
	return (tag / 2) >= y;

}
int Solve(int a,int b,int ans)
{
	if(b - a == 1)
		return b;
	int Mid = (a + b) / 2;
 	if( Ok(Mid,ans) )
		return Solve(a,Mid,ans);
		else
			return Solve(Mid,b,ans);
}
int main()
{
// n种道具，m个offer

	ans = 0;
	scanf("%d%d",&n,&m);
	for(int i = 1;i <= n;i++)
	{
		scanf("%d",&k[i]);
		ans = ans + k[i];
	}
	int d,t;
	for(int i = 1;i <= m;i++)
	{
		scanf("%d%d",&d,&t);
		Vec[d].push_back(t);
	}

	cout << Solve(0,2 * ans,ans) << endl;

	return 0;
}

/*************************************************************************
    > File Name: F.cc
    > Author: sqwlly
    > Mail: sqw.lucky@gmail.com
    > Created Time: 2019年08月13日 星期二 19时47分00秒
 ************************************************************************/

#include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#define dbg(args...)                                   \
    do{                                                \
	        cout << "\033[32;1m" << #args << " -> ";   \
         err(args);                                    \
      } while(0)
#else
#define dbg(...)
#endif
void err()
{
    cout << "\033[39;0m" << endl;
}
template <template <typename...> class T, typename t, typename... Args>
void err(T<t> a, Args... args)
{
    for (auto x : a) cout << x << ' ';
    err(args...);
}
template <typename T, typename... Args>
void err(T a, Args... args)
{
    cout << a << ' ';
    err(args...);
}
/****************************************************************************************************/
const int N = 2E5+10;
typedef long long LL;
vector<pair<int,int>> v;
vector<int> a,foo;
int n,m,dead[N];
LL sum;
bool check(LL x)
{
	LL cst = 0;
	foo = a;
	for(int i = 1; i <= n; ++i) dead[i] = 0;
	for(int i = 1; i <= m; ++i) {
		if(x >= v[i].first) {
			dead[v[i].second] = max(dead[v[i].second], v[i].first);
		}
	}
	int t = 0, cnt = 0;
	for(int i = 1; i <= m; ++i) {
		if(x >= v[i].first) {
			cst += v[i].first - v[i - 1].first;
			if(v[i].first == dead[v[i].second]) {
				t = min(cst, foo[v[i].second] * 1LL);
				cnt += t;
				foo[v[i].second] -= t;
				cst -= t;
			}
		}
	}
	return sum - cnt <= x;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in","r",stdin);
#endif
    ios::sync_with_stdio(false); cin.tie(0);
	int d,t,c;
	cin >> n >> m;
	a.emplace_back(0);
	for(int i = 1; i <= n; ++i) {
		cin >> c;
		sum += c;
		a.emplace_back(c);
	}
	sum *= 2;
	v.emplace_back(make_pair(0,0));
	for(int i = 0; i < m; ++i) {
		cin >> d >> t;
		v.emplace_back(make_pair(d,t));
	}
	sort(v.begin() + 1, v.end());
	LL l = 1, r = LLONG_MAX >> 1, ans = LLONG_MAX;
	while(l <= r) {
		LL mid = l + r >> 1;
		if(check(mid)) {
			ans = mid;
			r = mid - 1;
		}else{
			l = mid + 1;
		}
	}
	cout << ans << endl;
    return 0;
}

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;

int need[200005], take[2000006];
vector<int> sale[200005];
int n, m, sum;

bool check(int day){
    for(int i = 1; i <= day; i++) take[i] = 0;
    for(int i = 1; i <= n; i++){
        if(sale[i].size() == 0) continue;
        int l = 0, r = (int)sale[i].size() - 1;
        while(l != r){
            int mid = (l + r) / 2;
            if(sale[i][mid+1] <= day) l = mid + 1;
            else r = mid;
        }
        take[sale[i][l]] += need[i];
    }
    int money = 0, buy = 0;
    for(int i = 1; i <= day; i++){
        money++;
        buy += min(money, take[i]);
        money -= min(money, take[i]);
    }
    if(money >= 2 * (sum - buy)) return true;
    else return false;
}

int main()
{
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; i++){
        scanf("%d", &need[i]);
        sum += need[i];
    }
    for(int i = 1; i <= m; i++){
        int a, b;
        scanf("%d %d", &a, &b);
        sale[b].push_back(a);
    }
    for(int i = 1; i <= n; i++)
        sort(sale[i].begin(), sale[i].end());

    int l = sum, r = sum * 2;
    while(l != r){
        int mid = (l + r) / 2;
        if(check(mid)) r = mid;
        else l = mid + 1;
    }

    printf("%d\n", l);

    return 0;
}

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

typedef long long int lli;
typedef unsigned long long int ulli;
typedef pair<int,int> pii;

#define ones(x) __builtin_popcount(x)
#define onesl(x) __builtin_popcountl(x)
#define onesll(x) __builtin_popcountll(x)

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define scn(n) scanf("%d",&n)
#define scnll(n) scanf("%lld",&n)
#define scn2(n,m) scanf("%d%d",&n,&m)
#define scn3(n,m,w) scanf("%d%d%d",&n,&m,&w)
#define scn2ll(n,m) scanf("%lld%lld",&n,&m)
#define atoz(v) v.begin(),v.end()
#define ratoz(v) v.rbegin(),v.rend()
#define Fill(a,v) memset(a,v,sizeof(a))
#define sz(v) v.size()
#define fi first
#define se second
#define inf 1e9
#define sqr(x) x*x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define ten(n) (int)1e##n
#define tenll(n) (lli)1e##n
#define mod 1000000007
#define FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);

int Set(int N,int pos)
{
    return N=N | (1<<pos);
}
int reset(int N,int pos)
{
    return N = N & ~(1<<pos);
}
bool check(int N,int pos)
{
    return (bool)(N & (1<<pos));
}

///priority_queue< int, vector< int >, greater< int > > minHeap;

void mor(){cout<<"NO"; exit(0);}

#define N 500005

vector<int>v[N] , tv[N];

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

    ///FastIO;

    int n,m;
    scn2(n,m);

    int a[n+1] , tot = 0;

    for(int i=1; i<=n; i++){
        scn(a[i]);
        tot += a[i];
    }
    map<pii,bool>ase;
    for(int i=0; i<m; i++){
        int d,t;
        scn2(d,t);
        if(ase[pii(d,t)])continue;
        ase[pii(d,t)] = true;
        if(a[t]) v[d].pb(t);
    }

    int lo = 1 , hi = N , mid , day = N*3;

    while(lo<=hi){

        mid = (lo+hi)/2;

        if((tot*2)<=mid){
            day = min(mid,day);
            hi = mid-1;
        }
        else if(tot>mid) lo=mid+1;
        else{

            vector<bool>taken(n+2,0);

            vector<int>rem(n+2,0);
            for(int i=1; i<=n; i++) rem[i] = a[i];

            for(int i=mid; i>=1;  i--){
                tv[i].clear();
                for(int t : v[i]){
                    if(taken[t]==false){
                        taken[t] = true;
                        tv[i].pb(t);
                    }
                }
            }

            int now = tot , have = 0;

            for(int i=1; i<=mid && now; i++){

                have++;

                for(int t : tv[i]){
                    int take = min(have, rem[t]);
                    rem[t] -= take;
                    have -= take;
                    now -= take;
                }

            }
            if((now*2)<=have) now = 0;

            if(now == 0){
                day = min(day,mid);
                hi = mid-1;
            }
            else lo = mid+1;
        }
        //if(mid == 8)cout<<day<<" ---\n";
        if(mid == lo && lo == hi)break;
    }

    cout<<day;

    return 0;
    ///return main();
}

///sin and cos expect input in radians not degrees. so use , sin(degrees * pi / 180)

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

typedef long long int ll;
typedef long double lf;

#define pll pair<ll,ll>
#define vll vector<ll>
#define vpl vector<pair<ll,ll>>
#define mkp  make_pair
#define ppll pair<ll,pair<ll,ll>>
#define pb  push_back

#define ordered_set tree< ll , null_type , less<ll> , rb_tree_tag , tree_order_statistics_node_update >

using namespace __gnu_pbds;
using namespace std;

const int size = 2e5 + 5;

ll n,m;
vll a(size);
vll sale[size] , sales_day[size];

bool go(ll days){
    vll b = a;
    ll money = 0;

    for(int i = 1; i <= days ; i++){
        money++;
        for(int t : sales_day[i]){
            auto it = lower_bound(sale[t].begin(),sale[t].end(),days+1);
            it--;

            if(i < *it)continue;
            ll buy = min(money , b[t]);
            money -= buy;
            b[t] -= buy;
        }
    }

    for(int i = 1; i <= n; i++){
        money -= b[i]*2;
    }

    if(money >= 0)return true;
    return false;
}

void solve(){
    cin>>n>>m;
    ll low = 1 , high = 0 , mid , d , t , x;
    for(int i = 1 ; i <= n ; i++){
        cin>>a[i];
        high += a[i]*2;
    }
    for(int i = 1 ; i <= m ; i++){
        cin>>d>>t;
        sales_day[d].pb(t);
        sale[t].pb(d);
    }

    for(int i = 1; i <= n ; i++)sort(sale[i].begin(),sale[i].end());

    ll ans = high;
    while(low <= high){
        mid = (low+high)/2;
        if(go(mid)){
            ans = mid;
            high = mid-1;
        }else{
            low  = mid+1;
        }
    }
    cout<<ans;
}

int main(){
    ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	ll t = 1;
	//cin>>t;
	while(t--){
	    solve();
	}

}

#include<bits/stdc++.h>
using namespace std;
using LL = int64_t;
const int maxn=2e5+5;
int k[maxn],tk[maxn],eday[maxn];
struct Node {
    int x,y;
}node[maxn];
bool cmp(Node a,Node b) {
    return a.x<b.x;
}
LL n,m;

bool check(int mid) {
    int num=0,day=0;
    for(int i=1;i<=n;i++) tk[i]=eday[i]=0;
    for(int i=1;i<=m;i++) {
        if(node[i].x<=mid) eday[node[i].y]=node[i].x;
    }
    for(int i=1;i<=m;i++) {
        if(node[i].x<=mid) {
            if(node[i].x>day) num+=(node[i].x-day),day=node[i].x;
            if(eday[node[i].y]==node[i].x) {
                int cnt=min(num,k[node[i].y]-tk[node[i].y]);
                tk[node[i].y]+=cnt,num-=cnt;
            }
        }
        else break;
    }
    if(day<mid) num+=(mid-day);
    for(int i=1;i<=n;i++) {
        if(tk[i]<k[i]) num-=((k[i]-tk[i])*2);
    }
    if(num>=0) return true;
    return false;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>k[i];
    for(int i=1;i<=m;i++) cin>>node[i].x>>node[i].y;
    sort(node+1,node+1+m,cmp);
    int l=0,r=4e5+1;
    int ans=r;
    while(l<r) {
        int mid=(l+r)/2;
        if(check(mid)) ans=min(ans,mid),r=mid;
        else l=mid+1;
    }
    cout<<ans;
    return 0;
}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#define rep(i, s, e) for(int i = s; i < e; ++i)
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define P pair<int, int>
#define INF 0x3f3f3f3f
#define Mod 998244353
using namespace std;
typedef long long ll;
static const int N = 1005;
static const int MAX_N = 2e5 + 5;
int a[MAX_N], b[MAX_N];
vector<int>vec[MAX_N << 1];
int n;
bool judge(int x, int cnt, vector<int>vec[]){
    int day = x;    //花费天数(即可花费的bourle,因为每天可获得1bourle)
    for(int i = 1; i <= n; ++i) b[i] = a[i];
    int cur = 0;
    for(int i = x; i >= 1; --i){    //x天的优惠活动
        for(int j = 0; j < vec[i].size(); ++j){
            int t = vec[i][j];
            while(b[t] && day){     //尽可能多的在优惠中购买物品
                --b[t];
                --cnt;  //物品总数
                --day;  //bourle数量减少
            }
        }
        while(day >= i) ++cur, --day;   //borcle数目不能超过天数,多余部分只能用于未参与优惠的物品(这里条件控制的比较好,用if也行)
    }
    return cur >= 2 * cnt;  //未参与优惠的物品需2bourle
}
void solve(){
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    //ios::sync_with_stdio(false);
    int m;
    while(scanf("%d%d", &n, &m) != EOF){
        int cnt = 0;
        for(int i = 0; i < (MAX_N << 1); ++i) vec[i].clear();
        for(int i = 1; i <= n; ++i){
            scanf("%d", &a[i]);
            cnt += a[i];
        }
        for(int i = 0; i < m; ++i){
            int u, v;
            scanf("%d%d", &u, &v);
            vec[u].push_back(v);
        }
        int l = cnt, r = cnt << 1;
        int ans = 0;
        while(l <= r){
            int m = l + r >> 1;
            if(judge(m, cnt, vec)){
                r = m - 1;
                ans = m;
            }
            else l = m + 1;
        }
        printf("%d\n", ans);
    }
}
int main() {
    solve();
    return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>

using namespace std;

using namespace __gnu_pbds; // or pb_ds;

template<typename T, typename B = null_type>
using oset = tree<T, B, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order / order_of_key

template<typename T>
class minQ{
	deque<tuple<T, int, int> > p;
	T delta;
	int sz;
public:
	minQ() : delta(0), sz(0) {}
	inline int size() const{ return sz; }
	inline void add(T x){ delta += x; }
	inline void push(T x, int id){
		x -= delta, sz++;
		int t = 1;
		while(p.size() > 0 && get<0>(p.back()) >= x)
			t += get<1>(p.back()), p.pop_back();
		p.emplace_back(x, t, id);
	}
	inline void pop(){
		get<1>(p.front())--, sz--;
		if(!get<1>(p.front())) p.pop_front();
	}
	T getmin() const{ return get<0>(p.front())+delta; }
	int getid() const{ return get<2>(p.front()); }
};

namespace CHT {
	using ll = long long;
	struct Line {
		mutable ll m, b, p;
		bool operator<(const Line& o) const { return m < o.m; }
		bool operator<(ll x) const { return p < x; }
	};

	struct LineContainer : multiset<Line, less<>> { // CPP14 only
		// (for doubles, use inf = 1/.0, div(a,b) = a/b)
		const ll inf = LLONG_MAX;
		ll div(ll a, ll b) { // floored division
			return a / b - ((a ^ b) < 0 && a % b); }
		bool isect(iterator x, iterator y) {
			if (y == end()) { x->p = inf; return false; }
			if (x->m == y->m) x->p = x->b > y->b ? inf : -inf;
			else x->p = div(y->b - x->b, x->m - y->m);
			return x->p >= y->p;
		}
		void add(ll m, ll b) {
			auto z = insert({m, b, 0}), y = z++, x = y;
			while (isect(y, z)) z = erase(z);
			if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
			while ((y = x) != begin() && (--x)->p >= y->p)
				isect(x, erase(y));
		}
		ll query(ll x) {
			assert(!empty());
			auto l = *lower_bound(x);
			return l.m * x + l.b;
		}
	};
};

int INP,AM,REACHEOF;
#define BUFSIZE (1 << 12)
char BUF[BUFSIZE+1], *inp=BUF;
#define GETCHAR(INP) { \
    if(!*inp && !REACHEOF) { \
        memset(BUF,0,sizeof BUF);\
        int inpzzz = (int)fread(BUF,1,BUFSIZE,stdin);\
        if (inpzzz != BUFSIZE) REACHEOF = true;\
        inp=BUF; \
    } \
    INP=*inp++; \
}
#define DIG(a) (((a)>='0')&&((a)<='9'))
#define GN(j) { \
    AM=0;\
    GETCHAR(INP); while(!DIG(INP) && INP!='-') GETCHAR(INP);\
    if (INP=='-') {AM=1;GETCHAR(INP);} \
    j=INP-'0'; GETCHAR(INP); \
    while(DIG(INP)){j=10*j+(INP-'0');GETCHAR(INP);} \
    if (AM) j=-j;\
}

using ll = long long;
struct Frac {
	ll a, b;
	Frac(ll _a = 0, ll _b = 1) : a(_a), b(_b) {
		ll g = gcd(a, b);
		a /= g;
		b /= g;
		if(b < 0) a *= -1, b *= -1;
	}
	Frac operator+(const Frac &o) const {
		return {a * o.b + o.a * b, b * o.b};
	}
	Frac operator-(const Frac &o) const {
		return {a * o.b - o.a * b, b * o.b};
	}
	Frac operator*(const Frac &o) const {
		return {a * o.a, b * o.b};
	}
	Frac operator/(const Frac &o) const {
		return {a * o.b, b * o.a};
	}
	void print() const {
		printf("%lld/%lld", a, b);
	}
};

#define ff first
#define ss second

const int mod = 1e9+7;
int add(int a, int b) {
	return a + b < mod ? a + b : a + b - mod;
}
int mul(int a, int b) {
	return int(1LL * a * b % mod);
}
int fexp(int b, int e = mod - 2) {
	int ans = 1;
	while(e) {
		if(e & 1) ans = mul(ans, b);
		b = mul(b, b);
		e /= 2;
	}
	return ans;
}

template<typename T, size_t _n, size_t _m>
struct Matrix : std::array<array<T, _n>, _m> { // vector for dynamic size
#define ma(i) this->operator[](i)
#define mat this->_M_elems
  Matrix() {
    for(auto &row : *this) row.fill(0);
  }
  void identity() {
    for(auto &row : *this) row.fill(0);
    for(size_t i = 0; i < _n; i++) mat[i][i] = 1;
  }
  template<size_t _p>
  Matrix<T, _n, _p> operator*(const Matrix<T, _m, _p> &o) const {
    Matrix<T, _n, _p> ans;
    for(size_t i = 0; i < _n; i++) {
      for(size_t k = 0; k < _m; k++) {
        for(size_t j = 0; j < _p; j++) {
          ans[i][j] = add(ans[i][j], mul(mat[i][k], o[k][j]));
        }
      }
    }
    return ans;
  }
#undef mat
#undef ma
};

namespace flow {
	int ne = 0;
	const int N = 5105, E = 100000, oo = 1e6;
	struct Edge {
		int to, flow, cap;
	} edge[E];
	vector<int> g[N];

	int start = N - 1, target = N - 2;

	int vis[N], pass;

	int dfs(int u, int minE) {
		if(!minE) return 0;
		if(u == target) return minE;
		vis[u] = pass;
		for(int e : g[u]) {
			auto &ed = edge[e];
			if(vis[ed.to] == pass) continue;
			int tmp = dfs(ed.to, min(minE, ed.cap - ed.flow));
			if(tmp) {
				ed.flow += tmp;
				edge[e ^ 1].flow -= tmp;
				return tmp;
			}
		}
		return 0;
	}

	int solve() {
		int ans = 0, fl;
		while(1) {
			pass++;
			fl = dfs(start, oo);
			if(!fl) break;
			ans += fl;
		}
		return ans;
	}

	void addEdge(int u, int v, int cap = 1) {
		edge[ne] = {v, 0, cap};
		g[u].push_back(ne++);
		edge[ne] = {u, 0, 0};
		g[v].push_back(ne++);
	}
	void clean() {
		for(int i = 0; i < N; i++) g[i].clear();
		ne = 0;
	}
};

using ll = long long;

const int N = 1000005;
int fat[N], ifat[N];
int C(int n, int k) {
	if(k > n) return 0;
	return mul(mul(fat[n], fat[k]), fat[n - k]);
}
void inittt() {
	fat[0] = 1;
	for(int i = 1; i < N; i++) fat[i] = mul(i, fat[i - 1]);
	ifat[N - 1] = fexp(fat[N - 1]);
	for(int i = N - 2; i >= 0; i--) ifat[i] = mul(i + 1, ifat[i + 1]);
}

using Mat = Matrix<int, 2, 2>;

int n, m, k[N];
int d[N], t[N];

int f(int lim) {
	for(int i = 1; i + 1 <= lim; i++) {
		flow::addEdge(i, i + 1, flow::oo);
	}
	for(int i = 1; i <= lim; i++) {
		flow::addEdge(flow::start, i, 1);
	}
	for(int i = 0; i < m; i++) if(d[i] <= lim) {
		flow::addEdge(d[i], lim + t[i], flow::oo);
	}
	for(int i = 1; i <= n; i++) {
		flow::addEdge(lim + i, flow::target, k[i]);
	}

	int sum = flow::solve();
	int tot = 0;
	for(int i = 1; i <= n; i++) {
		tot += k[i];
	}
	flow::clean();
	return 2 * (tot - sum) <= lim - sum;
}

int main() {
	scanf("%d %d", &n, &m);

	for(int i = 1; i <= n; i++) scanf("%d", k + i);

	for(int i = 0; i < m; i++) scanf("%d %d", d + i, t + i);
	{
		vector<pair<int, int>> vec;
		for(int i = 0; i < m; i++) vec.emplace_back(d[i], t[i]);
		sort(vec.begin(), vec.end());
		for(int i = 0; i < m; i++) tie(d[i], t[i]) = vec[i];
	}

	int lo = 1, hi = 3000, ans = 3000;
	while(lo <= hi) {
		int mid = (lo + hi) / 2;
		if(f(mid)) ans = mid, hi = mid - 1;
		else lo = mid + 1;
	}

	printf("%d\n", ans);
}

#include<bits/stdc++.h>
#define rg register
#define fp( i , x , y ) for( rg int i=(x); i<=(y); ++i )
#define fq( i , x , y ) for( rg int i=(y); i>=(x); --i )
using namespace std ;
const int N = 2e5+10 ;
int n , a[N] , m , M , b[N] ;
vector <int> v[N] , on_s[N] ;
bool check( int L ) {
 // printf( "Now : %d\n" , L ) ;
  int _n = min( L , M ) ;
  int las = 0 ;
  memcpy( b , a , sizeof(b) ) ;
  fp( i , 1 , _n ) v[i].clear( ) ;
  fp( i , 1 , n ) {
    int l = on_s[i].size()-1 , now = -1 ;
    fp( j , 0 , l ) {
      int d = on_s[i][j] ;
      if( now < d && d <= L )
        now = d ;
	}
	v[now].push_back(i) ;
  }
  fp( i , 1 , _n ) {
     int l = v[i].size( )-1 ;
     las ++ ;
     fp( j , 0 , l ) {
       int x = v[i][j] ;
       if( b[x] == 0 ) continue ;
       if( !las ) break ;
       int now = min( b[x] , las ) ;
       b[x] -= now ; las -= now ;
    //   printf( "%d %d %d %d\n" , i , x , now , las ) ;
	 }
  }
  int tot = 0 ;
  fp( i , 1 , n ) tot += b[i] ;
  return las+(L-_n) >= tot*2 ;
}
signed main( ) {
   int x , y , tot = 0 ;
  scanf( "%d %d" , &n , &m ) ;
  fp( i , 1 , n ) scanf( "%d" , &a[i] ) , tot += a[i] ;
  fp( i , 1 , m ) {
    scanf( "%d %d" , &x , &y ) ;
    if( a[y] == 0 ) continue ;
    on_s[y].push_back(x) ;
    M = max( M , x ) ;
  }
  int l = tot , r = tot*2-1 , mid , ans = tot*2 ;
  while( l <= r ) {
    mid = l+r >> 1 ;
    if( check(mid) ) ans = mid , r = mid-1 ;
      else l = mid+1 ;
  }
  printf( "%d\n" , ans ) ;
  return 0 ;
}
/*
10 28
1 0 0 1 2 1 1 3 1 3
4 9
15 5
4 1
9 10
5 10
2 4
2 4
3 10
12 10
4 6
3 10
12 1
12 5
13 5
6 5
4 9
6 10
7 9
11 7
9 4
1 1
8 1
11 9
7 8
9 9
8 1
6 4
16 6
*/

//kanishk//
#include<bits/stdc++.h>
#define ll            long long
#define pb            push_back
#define ppb           pop_back
#define si            set <ll>
#define endl          '\n'
#define F             first
#define S             second
#define mii           map<ll ,ll >
#define msi           map<string,ll >
#define mis           map<ll , string>
#define rep(i,a,b)    for(ll  i=a;i<b;i++)
#define all(v)        v.begin(),v.end()
#define sort(v)         sort(all(v))
#define pii           pair<ll ,ll >
#define vi            vector<ll >
#define vs            vector<string>
#define sz(x)         (ll )x.size()
#define hell          1000000007
#define bs            binary_search
#define mp            make_pair
#define sp(n)         setprecision(n)
#define spl           " "
#define arr(a,n)        rep(i,0,n)cin>>a[i]
//#define abc   cin
//#define qwe   cout
using namespace std;
const ll int MAX=2005;
ll int a[2005],b[2005];
vi v[MAX];
ll int n;
ll int check(ll int d)
{
fill(b,b+MAX,0);
ll int B=0;
ll int has=d;
for(ll i=d;i>0;i--)
{
    has=min(has,i);
    for(ll j=0;j<v[i].size();j++)
    {ll int index=v[i][j];
    ll take=min(has,a[index]-b[index]);
    b[index]+=take;has-=take;B+=take;
    }
}
ll lft=d-B;
rep(i,0,n)
{
    lft-=2*(a[i]-b[i]);
}
if(lft>=0)
    return 1;

}

int main()
{ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
//ifstream abc("input.txt");
//ofstream qwe("output.txt");
ll int m;
cin>>n>>m;
rep(i,0,n)
{
    cin>>a[i];
}
rep(i,0,m)
{
    ll int d,t;
    cin>>d>>t;
    v[d].pb(--t);
}
ll int l,r,mid;
l=0;
r=MAX-4;
while(r>=l)
{
    mid=(l+r)/2;

    if(check(mid)==1)
        r=mid-1;
    else
        l=mid+1;
}
cout<<r+1;
return 0;
}

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int n, sum;
int a[1005], b[1005];
bool cost[10005][1005];
struct NODE{
	int d, b;
}t[1005];
bool cmp(NODE x, NODE y){
	if(x.d == y.d) return x.b < y.b;
	return x.d < y.d;
}
bool check(int x){
	int now = x, cnt = 0, day = 0;
	for(int i = 1;i <= n;i++) b[i] = a[i];
	for(int i = x;i >= 1;i--){
		for(int j = 1;j <= n;j++){
			if(cost[i][j]){
				cnt += min(now, b[j]);
				if(now < b[j]) b[j] -= now, now = 0;
				else now -= b[j], b[j] = 0;
			}
		}
		if(now >= i) now--, day++;
	}
	if((sum - cnt) <= day / 2) return 1;
	return 0;
}
int main(){
	int m, ans = 0;
	scanf("%d %d", &n, &m);
	for(int i = 1;i <= n;i++){
		scanf("%d", &a[i]);
		sum += a[i];
	}
	memset(cost, 0, sizeof(cost));
	for(int i = 1;i <= m;i++){
		scanf("%d %d", &t[i].d, &t[i].b);
		cost[t[i].d][t[i].b] = 1;
	}
	sort(t + 1, t + 1 + m, cmp);
	if(sum == 0) ans = 0;
	else{
		int l = 1, r = sum * 2;
		while(l <= r){
			int mid = (l + r) / 2;
			if(check(mid)){
				ans = mid;
				r = mid - 1;
			}
			else l = mid + 1;
		}
	}
	printf("%d\n", ans);
	return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef pair<int, int> ii;
typedef long long ll;

vector<int> sales[500001];
bool possible(int days, vector<int> neededOfType) {
	vector<int> saleDay;
	for (int i=0; i<neededOfType.size(); i++) {
		saleDay.push_back(-1);
	}
	for (int i=1; i<=days; i++)
		for (int j:sales[i])
			saleDay[j]=i;

	int money=0;
	for (int day=1; day<=days; day++) {
		money++;
		for (int item:sales[day]) {
			if (day!=saleDay[item]) continue;
			int toBuy=min(money, neededOfType[item]);
			money-=toBuy;
			neededOfType[item]-=toBuy;
		}
	}
	ll stillNeed=0;
	for (int &i:neededOfType)
		stillNeed+=i;
	return money>=2*stillNeed;
}

int main() {
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	int n, m; cin>>n>>m;
	vector<int> neededOfType;
	for (int i=0; i<n; i++) {
		int v; cin>>v;
		neededOfType.push_back(v);
	}
	vector<ii> allSales;//day, item
	for (int i=0; i<m; i++) {
		int day, item; cin>>day>>item;
		item--;
		sales[day].push_back(item);
	}
	int minDay=1, maxDay=500000;
	while (minDay!=maxDay) {
		int midDay=(minDay+maxDay)/2;
		if (possible(midDay, neededOfType)) {
			maxDay=midDay;
		}
		else {
			minDay=midDay+1;
		}
	}
	cout<<minDay<<endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL)
typedef long long ll;
typedef long double ld;
#define rep(i,a)  for(ll i=0; i< a; i++)
#define pb push_back
#define vl vector<ll>
#define trace(x)  cerr << #x << ": " << x << endl;
const ll N=2*1e5+5;
vector<ll> k(N);ll n,m;
vector<pair<ll,ll>> sale(N);
bool check(ll d)
{
	vector<ll> last(n,0);
	for(ll i=0;i<m;i++)
	{
		ll ji=sale[i].second;ll di=sale[i].first;
		if(di>d)continue;
		last[ji]=max(last[ji],di);
	}
	vector<vector<int>> off(200001);
	for(ll i=0;i<n;i++)
		if(last[i]!=0)off[last[i]].push_back(i);
	ll curmon=0;
	vector<ll> req(n);for(ll i=0;i<n;i++)req[i]=k[i];
	for(ll i=1;i<=d;i++)
	{
		curmon++;
		if(i>N)continue;
		if(!off[i].size())continue;
		for(auto u:off[i])
		{
			ll x=req[u];
			if(curmon>=x)
			{
				curmon-=x;req[u]=0;
			}
			else
			{
				req[u]-=curmon;curmon=0;break;
			}
		}

	}
	return accumulate(req.begin(),req.end(),0)*2<=curmon;
}
int main()
{
	fast;
	cin>>n>>m;
	for(ll i=0;i<n;i++)
		cin>>k[i];
	for(ll i=0;i<m;i++)
		cin>>sale[i].first>>sale[i].second,sale[i].second--;
	//sort(sale.begin(),sale.begin()+m);
	ll l=1;ll r=1e6;
	while(r>l)
	{
		ll m=(r+l)/2;
		if(check(m))
		{
			r=m;
		}
		else
		{
			l=m+1;
		}
	}
	cout<<l;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int MAX = 2e5+10;
int K[MAX],Last[MAX],Day[MAX],Type[MAX],N,M,max_ans=0;

int kenajabe(int type,int tk)
{
    int quo=0,am = K[type];
    if(tk>=am)quo=am;
    else quo = tk;
    return quo;
}
bool ok(int day)
{

    memset(Last,0,sizeof Last);
    vector<int>adj[day+5];

    for(int i=1;i<=M;i++)
    {
        if(Day[i]<=day)
        {
            Last[Type[i]]=max(Last[Type[i]],Day[i]);
        }
    }
    for(int i=1;i<=N;i++) adj[Last[i]].push_back(i);
    int curr=0,rem=max_ans;
    for(int i=1;i<=day;i++)
    {
        curr++;
        for(int j=0;j<adj[i].size();j++)
        {

            int quo = kenajabe(adj[i][j],curr);
            curr-=quo;
            rem-=quo;
        }

    }
    if(curr>1 && rem)
    {
        int q = curr/2;
        curr= curr - 2*q;
        rem-=q;
    }
    //cout<<alt<<" = "<<curr <<" = "<<rem<<endl;
    return (rem<=0);
}
int main ()
{

    cin >> N >> M;

    for(int i=1;i<=N;i++)
    {
        cin >> K[i];
        max_ans+=K[i];
    }

    for(int i=1;i<=M;i++)
    {
        cin >> Day[i] >> Type[i];
    }
    int lo=1,hi=2*max_ans;
    while(hi-lo>5)
    {
        int mid =(hi+lo)/2;
        if(ok(mid)) hi=mid;
        else lo=mid+1;
    }
    for(int i=max(1,lo-10);i<=min(2*max_ans,hi+10);i++)
    {
        if(ok(i)){
            cout<<i<<endl;
            return 0;
        }
    }
    return 0;
}

#include <bits/stdc++.h>
#define P pair<int,int>
#define fir first
#define sec second
#define N 200005
#define mod 998244353
#define ll long long
using namespace std;

int dir[4][2]={1,0,0,1,-1,0,0,-1};
int n,m,tot;
int a[N],tmp[N];
int last[N];
vector<int> v[N*2];

inline bool ck(int x){
	memset(last,0,sizeof(last));
	memcpy(tmp,a,sizeof(a));
	for(int i=1;i<=x;i++){
		for(int j=0;j<v[i].size();j++){
			int now=v[i][j];
			last[now]=i;
		}
	}
	//puts("ok");
	int money=0,ans=0;
	for(int i=1;i<=x;i++){
		money++;
		for(int j=0;j<v[i].size();j++){
			int now=v[i][j];
			while(last[now]==i&&money&&tmp[now])
				money--,ans++,tmp[now]--;

		}
		//puts("ok");
	}

	ans+=money/2;
	if(ans>=tot) return true;
	else return false;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]),tot+=a[i];
	int d,t;
	while(m--){
		scanf("%d%d",&d,&t);
		v[d].push_back(t);
	}
	//puts("ok");
	int ans=0;
	int l=1,r=tot*2;
	while(l<=r){
		int m=(l+r)>>1;
		if(ck(m)) ans=m,r-=1;
		else l+=1;
	}
	cout<<ans<<endl;
	return 0;
}

#include <bits/stdc++.h>

#define db(x) cerr << #x ": " << (x) << '\n';

using namespace std;

typedef long long ll;

typedef long double ld;

typedef pair<int,int> pii;

const int oo = 1e9;

const int MAXN = 5e5 + 100;

int N, M;

int A[MAXN];

vector<pii> vect;

int last[MAXN];

int sum = 0;

bool f(int mid)
{
    for(int i = 0 ; i < MAXN ; i++)last[i] = -1;
    for(int i = 0 ; i < vect.size() ; i++)
    {
        if(vect[i].first > mid)continue;
        last[vect[i].second] = vect[i].first;
    }
    int arr[MAXN];
    for(int i = 0 ; i < MAXN ; i++)arr[i] = 0;
    for(int i = 1 ; i <= N ; i++)
    {
        if(last[i] != -1)arr[last[i]] += A[i];
    }
    int cont = 0;
    for(int i = 1 ; i <= mid ; i++)
    {
        cont++;
        while(cont && arr[i])cont--,arr[i]--;
    }
    int gasto = mid-cont;
    int falta = sum-gasto;
    if(falta*2<=cont)
    {
        return true;
    }
    else
    {
        return false;
    }
}

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

    cin >> N >> M;

    for(int i = 1 ; i <= N ; i++)
    {
        cin >> A[i];
        sum += A[i];
    }

    for(int i = 1 ; i <= M ; i++)
    {
        int d, t;
        cin >> d >> t;
        vect.push_back({d,t});
    }

    sort(vect.begin(),vect.end());

    int a = 1, b = MAXN;
    int res = -1;
    while(a <= b)
    {
        int mid = (a+b)/2;
        if(f(mid))
        {
            b = mid-1;
            res = mid;
        }
        else
        {
            a = mid+1;
        }
    }

    cout << res << '\n';

    return 0;
}

#include<bits/stdc++.h>
//using namespace std;
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define rep(i,j,n) for(ll i=(ll)(j);i<(ll)(n);i++)
#define REP(i,j,n) for(ll i=(ll)(j);i<=(ll)(n);i++)
#define per(i,j,n) for(ll i=(ll)(j);(ll)(n)<=i;i--)
#define ll long long
#define ALL(a) (a).begin(),(a).end()
#define disup(A,key) distance(A.begin(),upper_bound(ALL(A),(ll)(key)))
#define dislow(A,key) distance(A.begin(),lower_bound(ALL(A),(ll)(key)))
#define pb emplace_back
#define mp std::make_pair
//
#define endl "\n"
//using std::endl;
using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::upper_bound;
using std::lower_bound;
using vi=vector<ll>;
using vii=vector<vi>;
using pii=std::pair<ll,ll>;
//constexpr ll MOD=1e9+7;
//
constexpr ll MOD=998244353;
//constexpr ll MOD=10000000;
//constexpr ll MOD=1e4;
constexpr ll MAX=3e6;
constexpr ll inf=(1ll<<60);
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template<typename T>
struct Segment_tree{
    ll N;
    T mem;
    vector<T> node;
    Segment_tree(vector<T> &X,T m):mem(m){
        ll sz=X.size();
        N=1;
        while(N<sz) N*=2;
        node.resize(2*N-1,mem);
        rep(i,0,sz) node[N-1+i]=X[i];
        per(i,N-2,0){
            node[i]=Compare(node[i*2+1],node[i*2+2]);
        }
    }
    T Compare(T &A,T &B){
        return std::max(A,B);
    }
    void update(ll X,T val){
        X+=N-1;
        node[X]=val;
        while(X>0){
            X=(X-1)/2;
            node[X]=Compare(node[X*2+1],node[X*2+2]);
        }
    }
    T Query(ll a,ll b,ll now,ll l,ll r){ //[a,b),[l,r)
        if(r<0) r=N;
        if(r<=a||b<=l) return mem;
        if(a<=l&&r<=b) return node[now];
        auto vl=Query(a,b,now*2+1,l,(l+r)/2),vr=Query(a,b,now*2+2,(l+r)/2,r);
        return Compare(vl,vr);
    }
};
template<typename T>
struct lazy_Segment_tree{
    int N;
    vector<T> node,lazy;
    T INF;
    lazy_Segment_tree(vector<T> X,T Y):INF(Y){
        N=1;
        while(X.size()>N) N*=2;
        node.resize(2*N-1,Y);
        lazy.resize(2*N-1);
        rep(i,0,X.size()) node[i+N-1]=X[i];
        per(i,N-2,0) node[i]=compare(node[i*2+1],node[i*2+2]);
    }
    T compare(T X,T Y){
        return std::max(X,Y);
    }
    T plus(T X,int l,int r){
        return X;
    }
    void eval(int now,int l,int r){
        if(lazy[now]==0) return;
        node[now]+=lazy[now];
        if(r-l>1){
            lazy[now*2+1]+=plus(lazy[now],l,r);
            lazy[now*2+2]+=plus(lazy[now],l,r);
        }
        lazy[now]=0;
    }
    void update(int a,int b,T add,int now=0,int l=0,int r=-1){
        if(r<0) r=N;
        eval(now,l,r);
        if(b<=l||r<=a) return;
        if(a<=l&&r<=b){
            lazy[now]+=add;
            eval(now,l,r);
        }
        else{
            update(a,b,add,now*2+1,l,(r+l)/2);
            update(a,b,add,now*2+2,(r+l)/2,r);
            node[now]=compare(node[now*2+1],node[now*2+2]);
        }
    }
    T Query(int a,int b,int now=0,int l=0,int r=-1){
        if(r<0) r=N;
        eval(now,l,r);
        if(b<=l||r<=a) return INF;
        if(a<=l&&r<=b) return node[now];
        return compare(Query(a,b,now*2+1,l,(r+l)/2),Query(a,b,now*2+2,(r+l)/2,r));
    }
};
struct Tree{
    int N;
    vii dp;
    vi dist;
    Tree(vii edge){
        N=edge.size();
        dp.resize(N);
        dist.resize(N,-1);
        for(int i=0;i<N;i++) dp[i].resize(30);
        dist[0]=dp[0][0]=0;
        std::queue<int> que;
        que.push(0);
        while(!que.empty()){
            int now=que.front(); que.pop();
            for(int i=0;i<edge[now].size();i++){
                int next=edge[now][i];
                if(dist[next]==-1){
                    dist[next]=dist[now]+1;
                    que.push(next);
                    dp[next][0]=now;
                }
            }
        }
        for(int i=1;i<30;i++){
            for(int j=0;j<N;j++) dp[j][i]=dp[dp[j][i-1]][i-1];
        }
    }
    int LCA(int X,int Y){
        if(dist[X]<dist[Y]) std::swap(X,Y);
        {
            int Z=dist[X]-dist[Y];
            for(int i=0;i<30;i++){
                if(Z&(1<<i)){
                    X=dp[X][i];
                }
            }
        }
        if(X==Y) return X;
        for(int i=29;i>=0;i--){
            if(dp[X][i]!=dp[Y][i]){
                X=dp[X][i];
                Y=dp[Y][i];
            }
        }
        return dp[X][0];
    }
};
struct Binary_indexed_tree{
    int N;
    vi bit;
    Binary_indexed_tree(int n):N(n){
        bit.resize(N+1,0);
    }
    void add(int x,ll a){
        for(x;x<=N;x+=(x&-x)) bit[x]+=a;
    }
    ll sum(int x){
        ll ret=0;
        for(x;x>0;x-=(x&-x)) ret+=bit[x];
        return ret;
    }
    ll lower_bound(ll X){
        if(sum(N)<X) return -1;
        ll ret=0,memo=1,sum=0;
        while(memo*2<=N) memo*=2;
        while(memo>0){
            if(memo+ret<=N&&sum+bit[memo+ret]<X){
                sum+=bit[memo+ret];
                ret+=memo;
            }
            memo/=2;
        }
        return ret+1;
    }
};
struct Union_Find{
    ll N;
    vi par;
    vi siz;
    Union_Find(int n):N(n){
        par.resize(N);
        siz.resize(N,1);
        rep(i,0,N) par[i]=i;
    }
    ll root(ll X){
        if(par[X]==X) return X;
        return par[X]=root(par[X]);
    }
    bool same(ll X,ll Y){
        return root(X)==root(Y);
    }
    void unite(ll X,ll Y){
        X=root(X);
        Y=root(Y);
        if(X==Y) return;
        par[X]=Y;
        siz[Y]+=siz[X];
        siz[X]=0;
    }
    ll size(ll X){
        return siz[root(X)];
    }
};
long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}
vi fac,finv,inv;
void COMinit() {
    fac.resize(MAX);
    finv.resize(MAX);
    inv.resize(MAX);
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}
ll COM(ll n,ll r){
    if(n<r||n<0||r<0) return 0;
    return fac[n]*finv[r]%MOD*finv[n-r]%MOD;
}
void comp(vi &A){
    std::map<ll,ll> memo;
    rep(i,0,A.size()) memo[A[i]]=0;
    ll cnt=1;
    for(auto &p:memo) p.second=cnt++;
    rep(i,0,A.size()) A[i]=memo[A[i]];
}
void dec(std::map<ll,ll> &mem,ll X){
    mem[X]--;
    if(mem[X]==0) mem.erase(X);
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    ll N,M; cin>>N>>M;
    vi A(N);
    rep(i,0,N) cin>>A[i];
    vi D(M),T(M);
    rep(i,0,M) cin>>D[i]>>T[i];
    ll left=0,right=1e9;
    while(left+1<right){
        ll mid=(left+right)/2;
        vector<pii> mem;
        rep(i,0,M){
            if(mid>=D[i]) mem.pb(mp(D[i],T[i]));
        }
        ll sum=0;
        rep(i,0,N){
            sum+=A[i];
        }
        sum*=2;
        sort(ALL(mem));
        ll now=0;
        vector<bool> flag(N);
        vector<pii> m;
        per(i,(ll)mem.size()-1,0){
            if(!flag[mem[i].second-1]) m.pb(mem[i]);
            flag[mem[i].second-1]=1;
        }
        mem=m;
        sort(ALL(mem));
        for(auto p:mem){
            ll X,Y; std::tie(X,Y)=p;
            ll Z=A[Y-1];
            if(X-now<Z){
                sum-=X-now;
                now=X;
            }
            else{
                sum-=Z;
                now+=Z;
            }
        }
        if(sum<=mid) right=mid;
        else left=mid;
    }
    cout<<right<<endl;
}

#include <bits/stdc++.h>
#define ll long long
#define MOD 998244353
#define CAP 1000000
#define inf 10000000000000000LL
#define pii pair<ll,ll>
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define endl '\n'
#define sz(v) v.size()
#define all(v)    v.begin(),v.end()
#define fast  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//#define int ll
using namespace std;
ll power(ll x,ll y, ll md=MOD){ll res = 1;x%=md;while(y>0){if(y&1)res = (res*x)%md;x = (x*x)%md;y = y>>1;}return res%md;}

signed main() {
	fast;
	ll n,m;
	cin>>n>>m;
	vector<ll> vm(n);
	ll tot=0;
	for(int i=0;i<n;i++) cin>>vm[i],tot+=vm[i];
	std::vector<pii > v(m);
	for(int i=0;i<m;i++) cin>>v[i].f>>v[i].s,v[i].s--;
	sort(all(v));

	ll l=tot, r=400001,mid,ans=400001;
	while(l<=r){
		mid=(l+r)/2;
		std::vector<ll> vc=vm;
		ll used=0, purchase=0;
		ll c = mid;
		for(ll i=m-1;i>-1;i--){
			//cout<<"$"<<i<<" "<<v[i].f<<" "<<v[i].s<<" "<<vc[v[i].s]<<"\n";
			assert(v[i].s<n);
			if(v[i].f<=mid&&vc[v[i].s]>0){
				if(i!=m-1) {
					used-=v[i+1].f-v[i].f;
					used=max(used,0LL);
					used=min(used,v[i].f);
				}
				c=min(c,v[i].f);
				ll temp=min(vc[v[i].s],c);
				if(v[i].f-used!=c) cerr<<i<<" "<<v[i].f<<" "<<used<<" "<<c<<endl;
				//assert(v[i].f-used==c);
				vc[v[i].s]-=temp;
				purchase+=temp;
				used+=temp;
				c-=temp;
			}
		}
		ll daysReq=purchase+2*(tot-purchase);
		//cout<<l<<" "<<r<<" "<<mid<<" -- "<<purchase<<" "<<daysReq<<endl;
		if(daysReq<=mid) {
			ans=min(ans,mid);
			r=mid-1;
		}
		else l=mid+1;
	}
	cout<<ans;
}

#include<bits/stdc++.h>

using namespace std;

#define ff first
#define ss second

int main()
{
    int n,m;
    cin >> n >> m;
    int a[n];
    long long int sum=0;
    for(int i=0;i<n;i++)
    {
        cin >> a[i];
        sum+=a[i];
    }
    pair<int,int> b[m];
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin >> x >> y;
        b[i]=make_pair(x,y);
    }
    int late[n]={0};
    sort(b,b+m);
    /*for(int i=0;i<m;i++)
        cout << b[i].ff << " ";
    cout << endl;*/
    long long int low=0,high=2*sum,ans=-1;
    while(low<=high)
    {
        long long int mid=(high+low)/2,t=sum,t2=mid;
        int j=0,pre=0;
        int d[n];
        for(int i=0;i<n;i++)
            d[i]=a[i];
        for(int i=0;i<m;i++)
        {
            if(b[i].ff<=mid)
                late[b[i].ss-1]=b[i].ff;
        }
        for(int i=0;i<m&&b[i].ff<=mid;i++)
        {
            if(late[b[i].ss-1]!=b[i].ff)
                continue;
            j+=b[i].ff-pre;
            t-=min(d[b[i].ss-1],j);
            int t1=d[b[i].ss-1];
            d[b[i].ss-1]-=min(d[b[i].ss-1],j);
            j=max(0,j-t1);
            t2=mid-b[i].ff;
            pre=b[i].ff;
            //cout << b[i].ff << " " << t << endl;
        }
        j+=t2;
        if(2*t<=j)
        {
            ans=mid;
            high=mid-1;
        }
        else
            low=mid+1;
    }
    cout << ans;
    return 0;
}

#include <bits/stdc++.h>
#define ll long long
#define MOD 998244353
#define CAP 1000000
#define inf 10000000000000000LL
#define pii pair<ll,ll>
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define endl '\n'
#define sz(v) v.size()
#define all(v)    v.begin(),v.end()
#define fast  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//#define int ll
using namespace std;
ll power(ll x,ll y, ll md=MOD){ll res = 1;x%=md;while(y>0){if(y&1)res = (res*x)%md;x = (x*x)%md;y = y>>1;}return res%md;}

signed main() {
	fast;
	ll n,m;
	cin>>n>>m;
	vector<ll> vm(n);
	ll tot=0;
	for(int i=0;i<n;i++) cin>>vm[i],tot+=vm[i];
	std::vector<pii > v(m);
	for(int i=0;i<m;i++) cin>>v[i].f>>v[i].s,v[i].s--;
	sort(all(v));

	ll l=tot, r=400001,mid,ans=400001;
	while(l<=r){
		mid=(l+r)/2;
		std::vector<ll> vc=vm;
		ll used=0, purchase=0;
		ll c = mid;
		for(ll i=m-1;i>-1;i--){
			//cout<<"$"<<i<<" "<<v[i].f<<" "<<v[i].s<<" "<<vc[v[i].s]<<"\n";
			assert(v[i].s<n);
			if(v[i].f<=mid&&vc[v[i].s]>0){
				/*if(i!=m-1) {
					used-=v[i+1].f-v[i].f;
					used=max(used,0LL);
				}*/
				c=min(c,v[i].f);
				ll temp=min(vc[v[i].s],c);
				vc[v[i].s]-=temp;
				purchase+=temp;
				//used+=temp;
				c-=temp;
			}
		}
		ll daysReq=purchase+2*(tot-purchase);
		//cout<<l<<" "<<r<<" "<<mid<<" -- "<<purchase<<" "<<daysReq<<endl;
		if(daysReq<=mid) {
			ans=min(ans,mid);
			r=mid-1;
		}
		else l=mid+1;
	}
	cout<<ans;
}

#include <bits/stdc++.h>

using namespace std;
#define fl(i,a,b) for(int i=a;i<b;i++)
#define ll long long
#define endl '\n'
#define pb push_back
#define ff first
#define ss second
#define mod 998244353
#define mxx 300005
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
int arr[mxx],val[mxx],temp[mxx];
vector<pair<int,int> > v;
int n,m;
ll sum=0;
// function to check if it can be done in x days.Greedily trying to purchase anything as late as I can.
bool check(int x)
{
	int lastSale = upper_bound(v.begin(),v.end(),make_pair(x,mod) ) - v.begin();
	lastSale--;                                       // last sale < xth day
	int barr = x, extra = 0,used = 0;
	fl(i,0,n)
	{
		temp[i]=arr[i];
	}
	for(int i=lastSale;i>=0;i--)
	{
		int day = v[i].ff;                        // current day
		int id = v[i].ss;                         // type id
		int quantity = arr[id];                   // quantity of type needed
		extra += max(0,barr-day);                 // Extra barrels that we will earn after current day and can't be used now
		barr = min(barr,day);                     // quantity that can be purchased in sale
		int usedToday = min(quantity,barr);       // purchased today from sale
		barr -= usedToday;                        // amount spent today
		arr[id] -= usedToday;                     // quantity of type needed
		used += usedToday;                        // total purchased
	//	cout<<day<<" "<<id<<" "<<used<<" "<<extra<<" " <<barr<<endl;
	}
	fl(i,0,n)
	{
		arr[i]=temp[i];
	}
	extra += barr;                               // total extra burrels left to puchase wihout sale
	int left = sum - used;                       // quantity left
	if(extra >= 2*left)                          // if I can purchase remaining with the burrels
		return 1;
	else return 0;
}
main()
{
	ll mx=mod;

	cin>>n>>m;

	fl(i,0,n)
	{
		cin>>arr[i];
		sum+=arr[i];
		val[i]=mod;
	}
	fl(i,0,m)
	{
		int x,y;
		cin>>x>>y;
		v.push_back(make_pair(x,y-1));
	}
	sort(v.begin(),v.end());
	ll curr=0,barr=0,ans=0,fans=2*sum;

	int low=1,high=fans,mid;
	while(low<high)                       // binary search on the optimal answer
	{
		mid = (low+high)/2;
		if(check(mid))
		{
			high = mid;
		}
		else low = mid+1;
	//	cout<<mid<<" "<<check(mid)<<endl;
	}
	cout<<low;

}

/* sun */
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
typedef long long ll;
using namespace std;
#define MAXN 500006
int n , m , s;
int nd[MAXN];
bool use[MAXN];
int Ds[MAXN] , idx[MAXN];
vector<int> tps[MAXN];
int ND[MAXN];
bool chk( int d ) {
	int ok = 0 , used = 0 , flag = 0;
	for( int i = 1 ; i <= n ; ++ i ) ND[i] = nd[i];
	for( int i = d ; i >= 1 ; -- i ) {
		if( used > 0 ) --used;
		if( Ds[i] ) {
			for( int j = 0 ; j < tps[i].size() ; ++ j ) {
				if( ND[tps[i][j]] > 0 && used <= i ) {
					int maxg = i - used;
					if( ND[tps[i][j]] < maxg )
						used += ND[tps[i][j]] , ok += ND[tps[i][j]] , ND[tps[i][j]] = 0;
					else
						used = i , ok += maxg;
				}
				if( used == i ) break;
			}
		}
		if( used == i ) break;
	}
	if( 2 * s - ok <= d ) return true;
	return false;
}

int main() {
	//freopen("input","r",stdin);
	cin >> n >> m;
	for( ll i = 1 ; i <= n ; ++ i ) scanf("%lld",&nd[i]) , s += nd[i];
	for( ll i = 1 , u , v ; i <= m ; ++ i ) {
		scanf("%lld%lld",&v,&u);
		++ Ds[v];
		tps[v].push_back(u);
	}
	ll l = 1 , r = 2*s , mid;
	while( l <= r ) {
		mid = l + r >> 1;
		if( chk( mid ) ) r = mid - 1;
		else l = mid + 1;
	}
	cout << l << endl;
}

#include<bits/stdc++.h>
using namespace std;
const int M=4e5+5;
int n,m,k[M],b[M],ans;

inline void read(int &x)
{
	char ch=getchar();int u=0,f=1;
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch)){u=(u<<1)+(u<<3)+(ch^48);ch=getchar();}x=u*f;
}

struct node
{
	int d,w;
}t[M];

bool cmp(node x,node y){return x.d<y.d;}

bool check(int x)
{
	int q=x,qq=0,tt=0;
	for(int i=1;i<=n;i++)b[i]=k[i];
	for(int i=m;i>=1;i--)if(x>=t[i].d){tt=i;q=t[i].d;break;}
	for(int i=tt;i>=1;i--)
	{
		q=min(q,t[i].d);
		if(b[t[i].w]&&q)
		{
			int xx=min(q,b[t[i].w]);
			qq+=xx;
			q-=xx;
			b[t[i].w]-=xx;
		}
	}
	for(int i=1;i<=n;i++)if(b[i])qq+=b[i]*2;
	if(qq>x)return 0;
	return 1;
}

int main()
{
	read(n),read(m);
	for(int i=1;i<=n;i++)read(k[i]);
	for(int i=1;i<=m;i++)read(t[i].d),read(t[i].w);
	sort(t+1,t+m+1,cmp);
	int l=1,r=400005;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(check(mid))ans=mid,r=mid-1;
		else l=mid+1;
	}
	cout<<ans;
	return 0;
}

#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<string.h>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<map>
#include<stack>
#include<list>
#define pii pair<int, int>
#define pll pair<LL, LL>
#define pil pair<int, LL>
#define pli pair<LL, int>
#define mp make_pair
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const LL LLINF = 1e18;
const int INF = 1e9;
const int MOD = 20101009;
const int HMOD = 999959;
const int VMOD = 5000000;
const int MAXN = 2e5+10;
const int MAXM = 5e5+10;
const int INV = 10050505;
const LL LLINV = 1e18;
const double eps = 1e-3;
int dirx[5] = {0, -1, 1, 0, 0}, diry[5] = {0, 0, 0, -1, 1};

int n, m;
int k[MAXN], tmp[MAXN];
vector<int> d[MAXN];

bool check(int x)
{
    for (int i = 1;i <= n; ++i) tmp[i] = k[i];
    int sum = 0;
    int c = x;
    for (int i = min(200000, x);i >= 1; --i)
    {
        c = min(c, i);
        for (auto t: d[i]) if (tmp[t])
        {
            int x = min(min(c, i), tmp[t]);
            sum += x;
            c -= x;
            tmp[t] -= x;
        }
        /* cout << c << endl; */
    }
    int cnt = 0;
    for (int i = 1;i <= n; ++i) cnt += tmp[i];
    return x-sum >= cnt*2;
}

int main()
{
IOS;
    scanf("%d%d", &n, &m);
    for (int i = 1;i <= n; ++i)
        scanf("%d", &k[i]);
    for (int i = 1;i <= m; ++i)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        d[x].pb(y);
    }
    int l = 1, r = 1e6;
    int ans = r;
    while(l <= r)
    {
        int mid = (l+r)/2;
        if (check(mid))
        {
            ans = mid;
            r = mid-1;
        }
        else l = mid+1;
    }
    printf("%d\n", ans);

    return 0;
}

//new.cpp
/*
Author : Jennie Kim (김제니)
BLΛƆKPIИK in your area !

*/

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <limits>
#include <string>
#include <vector>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;

typedef double D;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;

#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define remove erase
#define endl '\n'

const double eps = 1e-9;
const int INF = 1061109567;
const LL LINF = 4557430888798830399LL;
const LL MOD = 1000000007;
const int dx[8] = {1,0,-1,0,1,1,-1,-1};
const int dy[8] = {0,1,0,-1,1,-1,1,-1};
const double PI = 3.141592653589793;

inline void fasterios(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

LL n,m,t;
LL Limit[400005];
LL Cursale[400005];
LL CurLimit[400005];
vector <LL> Sale[400005];

int main(){
	cin >> t >> m;
	for(int i = 1;i <= t;i++){
		cin >> Limit[i];
		n += Limit[i];
	}
	for(int i = 1;i <= m;i++){
		LL Day,Type;
		cin >> Day >> Type;
		Sale[Day].pb(Type);
	}
	LL Left = 0;
	LL Right = n;
	//Binary search the microtransaction bought by sale
	while(Left < Right){
		memset(CurLimit,0,sizeof(CurLimit));
		LL mid = (Left+Right+1)>>1;
		LL curans = 2*n-mid;
		LL used = 0;
		for(int i = curans;i >= 1;i--){
			Cursale[i] = 0;
			for(int j = 0;j < Sale[i].size();j++){
				LL CurrentUsed = min(mid-used,Limit[Sale[i][j]]-CurLimit[Sale[i][j]]);
				CurLimit[Sale[i][j]] += CurrentUsed;
				used += CurrentUsed;
				Cursale[i] += CurrentUsed;
			}
		}
		if(used < mid){
			Right = mid-1;
			continue;
		}
		bool flag = 1;
		used = 0;
		for(int i = 1;i <= curans;i++){
			used += Cursale[i];
			if(used > i){
				flag = 0;
				break;
			}
		}
		if(flag) Left = mid;
		else Right = mid-1;
	}
	cout << 2*n-Left << endl;
    return 0;
}

#include <iostream>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
using namespace std;
typedef long long ll;
#define vec vector
#define ms multiset
#define pb push_back
#define pll pair<long long, long long>
#define pii pair<int, int>
#define vi vector<int>
#define vll vector<long long>
#define int long long
#define _ << " " <<
#define all(a) a.begin(), a.end()
#define srt(a) std::sort(a.begin(), a.end())
template<typename T>
vector<T> _set_to_vec(std::set<T> z)
{
	vector<T> w;
	auto it = z.begin();
	while (it != z.end())
		w.push_back(*it++);
	return w;
}
template<typename T>
void pop_front(std::vector<T>& vec)
{
	vec.erase(vec.begin());
}

vector<long long> z_function(string s) {
	long long n = (long long)s.length();
	vector<long long> z(n);
	for (long long i = 1, l = 0, r = 0; i < n; ++i) {
		if (i <= r)
			z[i] = min(r - i + 1, z[i - l]);
		while (i + z[i] < n && s[z[i]] == s[i + z[i]])
			++z[i];
		if (i + z[i] - 1 > r)
			l = i, r = i + z[i] - 1;
	}
	return z;
}
struct point {
	double x, y;
	point(double x, double y) :x(x), y(y) {};
	point() {};
};

point operator+(point a, point b) { return point(a.x + b.x, a.y + b.y); };
point operator-(point a, point b) { return point(a.x - b.x, a.y - b.y); };
double operator*(point a, point b) { return (a.x * b.x + a.y * b.y); };

double operator^(point a, point b) { return (a.x * b.y - a.y * b.x); };
double operator%(point a, point b) { return atan2(a ^ b, a * b); }
double eps = 1e-13;
template<typename T>
bool equals(T a, T b)
{
	return abs(a - b) <= eps;
}
template<typename T>
int sign(T a)
{
	return a < 0 ? -1 : (a > 0 ? 1 : 0);
}
#define pt point
inline double area(pt a, pt b, pt c) {
	return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
inline char intersect_1(double a, double b, double c, double d) {
	if (a > b)  swap(a, b);
	if (c > d)  swap(c, d);
	return max(a, c) <= min(b, d);
}

char intersect(pt a, pt b, pt c, pt d) {
	return intersect_1(a.x, b.x, c.x, d.x)
		&& intersect_1(a.y, b.y, c.y, d.y)
		&& area(a, b, c) * area(a, b, d) <= 0
		&& area(c, d, a) * area(c, d, b) <= 0;
}

double pi = acos(-1.0);
double dist(point p)
{
	return sqrt(p.x * p.x + p.y * p.y);
}

bool cmpr(pt a, pt b)
{
	if (equals((a ^ b), (double)0))
		return dist(a) < dist(b);
	else return (a ^ b) < 0;
}
bool cmp(pt a, pt b) {
	return a.x < b.x || a.x == b.x && a.y < b.y;
}

bool cw(pt a, pt b, pt c) {
	return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < 0;
}

bool ccw(pt a, pt b, pt c) {
	return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0;
}

void convex_hull(vector<pt>& a) {
	if (a.size() == 1)  return;
	sort(a.begin(), a.end(), &cmp);
	pt p1 = a[0], p2 = a.back();
	vector<pt> up, down;
	up.push_back(p1);
	down.push_back(p1);
	for (size_t i = 1; i < a.size(); ++i) {
		if (i == a.size() - 1 || cw(p1, a[i], p2)) {
			while (up.size() >= 2 && !cw(up[up.size() - 2], up[up.size() - 1], a[i]))
				up.pop_back();
			up.push_back(a[i]);
		}
		if (i == a.size() - 1 || ccw(p1, a[i], p2)) {
			while (down.size() >= 2 && !ccw(down[down.size() - 2], down[down.size() - 1], a[i]))
				down.pop_back();
			down.push_back(a[i]);
		}
	}
	a.clear();
	for (size_t i = 0; i < up.size(); ++i)
		a.push_back(up[i]);
	for (size_t i = down.size() - 2; i > 0; --i)
		a.push_back(down[i]);
}

typedef string str;

template<typename T>
inline istream& operator >>(istream& in, vec<T>& a) {
	for (int i = 0; i < a.size(); i++) in >> a[i];
	return in;
}

template<typename T>
inline ostream& operator <<(ostream& out, vec<T>& a) {
	for (int i = 0; i < a.size(); i++) out << a[i] << " ";
	return out;
}

template<typename T, typename E>
inline istream& operator >>(istream& in, pair<T, E>& a) {
	in >> a.first >> a.second;
	return in;
}

template<typename T>
T gcd(T a, T b) {
	T c;
	while (b) {
		c = a % b;
		a = b;
		b = c;
	}
	return a;
}

template<typename T>
T lcm(T a, T b) {
	return (a / gcd(a, b)) * b;
}

vector<int> prefix_function(string s) {
	int n = (int)s.length();
	vector<int> pi(n);
	for (int i = 1; i < n; ++i) {
		int j = pi[i - 1];
		while (j > 0 && s[i] != s[j])
			j = pi[j - 1];
		if (s[i] == s[j])  ++j;
		pi[i] = j;
	}
	return pi;
}

int binpow(int a, int n) {
	if (n == 0)
		return 1;
	if (n & 1)
		return binpow(a, n - 1) * a;
	else {
		int b = binpow(a, n >> 1);
		return b * b;
	}
}

vector<int> primes(int N) {
	vector<int> lp(N + 1);
	vector<int> pr;

	for (int i = 2; i <= N; ++i) {
		if (lp[i] == 0) {
			lp[i] = i;
			pr.push_back(i);
		}
		for (int j = 0; j < (int)pr.size() && pr[j] <= lp[i] && i * pr[j] <= N; ++j)
			lp[i * pr[j]] = pr[j];
	}
	return pr;
}

typedef vec<vi> matrix;

matrix operator*(matrix& a, matrix& b) {
	matrix m;
	int cx = a[0].size(), cy = b.size();
	m.resize(cx);
	for (int i = 0; i < cx; i++)
		m[i].resize(cy);
	for (int i = 0; i < cx; i++) {
		for (int j = 0; j < cy; j++) {
			int res = 0;
			for (int p = 0; p < b[0].size(); p++)
				res += a[i][p] * b[p][j];
			m[i][j] = res;
		}
	}
	return m;
}

int cnt = 0;
matrix pow(matrix& a, int b) {
	if (b == 1)
		return a;
	cnt++;
	if (b & 1)
	{
		auto r = pow(a, b - 1);
		r = r * a;
		return r;
	}
	else {
		auto r = pow(a, b / 2);
		r = r * r;
		return r;
	}
}
set<int> printDivisors(int n)
{
	set<int> r;
	// Note that this loop runs till square root
	for (int i = 1; i <= sqrt(n); i++)
	{
		if (n % i == 0)
		{
			// If divisors are equal, print only one
			if (n / i == i)
				r.insert(i);

			else // Otherwise print both
				r.insert(i), r.insert(n / i);
		}
	}
	return r;
}

int n, m, s = 0;
vi a;
map<int, vector<int>> mp;

inline bool check(int k) {
	auto aa = a;
	int bal = k;
	for (int i = k ; i; i--) {
		if (mp.count(i)) {
			int w = 0;
			k = min(k, i);
			for (auto &e : mp[i]) {
				bal -= min(k, aa[e]);
				int ww = aa[e];
				aa[e] -= min(k, aa[e]);
				k -= min(k, ww);
			}
		}
	}
	int cnt = 0;
	for (int i = 0; i < n; i++)
		cnt += aa[i];
	return cnt * 2 <= bal;

}

inline void solve() {
	cin >> n >> m;
	a.resize(n);
	cin >> a;
	for (int i = 0; i < n; i++) s += a[i];
	set<pii> b;
	for (int i = 0; i < m; i++) {
		int u, l;
		cin >> u >> l;
		b.insert({ u, l - 1 });
	}
	for (auto e : b)
		if (a[e.second])
			mp[e.first].pb(e.second);

	int l = 0, r = 1 + (s << 1);
	while (l < r - 1) {
		int m = (l + r) / 2;
		if (check(m))
			r = m;
		else
			l = m;
	}
	cout << r;
}

int32_t main() {
	ios::sync_with_stdio(false);
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	solve();
	int k;
	cin >> k;
}

#include<bits/stdc++.h>
using namespace std;
long long n,m,i;
vector<long long> k;
vector<pair<long long,long long>> sale(1007);
bool rightday(long long day)
{
	vector<long long> lst(n,-1);
	for(i=0;i<m;i++)
	{
		if(sale[i].first<=day)
		{
			lst[sale[i].second]=max(lst[sale[i].second],sale[i].first);
		}
	}
	vector<vector<long long>> track(1007);
	for(i=0;i<n;i++)
	{
		if(lst[i]!=-1)
		{
			track[lst[i]].push_back(i);
		}
	}
	vector <long long> tempk=k;
	long long mon=0;
	for(i=0;i<=day;i++)
	{
		++mon;
		if(i>1000)
			continue;
		for(auto it: track[i])
		{
			if(mon>=k[it])
			{
				mon-=tempk[it];
				tempk[it]=0;
			}
			else
			{
				tempk[it]-=mon;
				mon=0;
				break;
			}
		}
	}
	long long sum=0;
	for(i=0;i<n;i++)
	{
		sum+=(tempk[i]*2);
	}
	if(mon>=sum)
		return true;
	else
		return false;
}
int main()
{
	cin >> n >> m;
	k = vector<long long>(n);
	for(i=0;i<n;++i)
	{
		cin>>k[i];
	}
	for(long long g=0;g<m;g++)
	{
		//cout<<"heey"<<endl;
		cin >> sale[g].first >> sale[g].second;
		--sale[g].first;
		--sale[g].second;
	}
	//cout<<"hey"<<endl;
	long long l = 0, r = 400000;
	long long mid;
	while (r - l > 1)
	{
		mid = (l + r) >> 1;
		if (rightday(mid)) r = mid;
		else l = mid;
	}
	if(rightday(mid-1))
	{
		cout<<mid<<endl;
	}
	else if(rightday(mid))
	{
		cout<<mid+1<<endl;
	}
	else if(rightday(mid+1))
	{
		cout<<mid+2<<endl;
	}
}

#include<bits/stdc++.h>
using namespace std;
long long n,m,i;
vector<long long> k;
vector<pair<long long,long long>> sale(1007);
bool rightday(long long day)
{
	vector<long long> lst(n,-1);
	for(i=0;i<m;i++)
	{
		if(sale[i].first<=day)
		{
			lst[sale[i].second]=max(lst[sale[i].second],sale[i].first);
		}
	}
	vector<vector<long long>> track(1007);
	for(i=0;i<n;i++)
	{
		if(lst[i]!=-1)
		{
			track[lst[i]].push_back(i);
		}
	}
	vector <long long> tempk=k;
	long long mon=0;
	for(i=0;i<=day;i++)
	{
		++mon;
		if(i>1000)
			continue;
		for(auto it: track[i])
		{
			if(mon>=k[it])
			{
				mon-=tempk[it];
				tempk[it]=0;
			}
			else
			{
				tempk[it]-=mon;
				mon=0;
				break;
			}
		}
	}
	long long sum=0;
	for(i=0;i<n;i++)
	{
		sum+=(tempk[i]*2);
	}
	if(mon>=sum)
		return true;
	else
		return false;
}
int main()
{
	cin >> n >> m;
	k = vector<long long>(n);
	for(i=0;i<n;++i)
	{
		cin>>k[i];
	}
	for(long long g=0;g<m;g++)
	{
		//cout<<"heey"<<endl;
		cin >> sale[g].first >> sale[g].second;
		--sale[g].first;
		--sale[g].second;
	}
	//cout<<"hey"<<endl;
	for(int f=0;f<=2000;f++)
	{
		//cout<<"i"<<endl;
		if(rightday(f))
		{
			cout<<f+1<<endl;
			break;
		}
	}
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
	ll n,m,i,sum=0,cnt,money,mn,x,y,len,j,ans;
	cin>>n>>m;
	ll arr[20001],a[20001],l,k,r,mid;
	vector<ll> brr[20001];
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		sum+=arr[i];
	}
	sum*=2;
	for(i=0;i<m;i++)
	{
		cin>>x>>y;
		brr[x].push_back(y);
	}
	l=1;
	r=sum;
	cnt=r;
	while(r>=l)
	{
		mid=(l+r)/2;
		for(i=1;i<=n;i++)
			a[i]=arr[i];
		money=mid;
		ans=sum;
		for(j=min(mid,(ll)20000);j>0;j--)
		{
			money=min(money,j);
			len=brr[j].size();
			for(k=0;k<len;k++)
			{

				mn=min(money,a[brr[j][k]]);
				ans-=mn;
				a[brr[j][k]]-=mn;
				money-=mn;
			}
		}
		if(ans<=mid)
		{
			cnt=mid;
			r=mid-1;
		}
		else
			l=mid+1;
	}
	cout<<cnt<<endl;
	return 0;
}

#include<bits/stdc++.h>
#include<math.h>
#include<algorithm>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
const double pi=3.141592653589;
long long int mod = 1000000007;
const long long int inf = 1e9;
const long long int inff = 9000000000000000000;
long double eps = 1e-9;
#define pry  cout<<"YES\n"
#define prn  cout<<"NO\n"
#define prm cout<<"-1\n"
#define nl cout<<"\n"
#define loop(i,a,b) for(ll i=a;i<b;i+=1)
#define rloop(i,a,b) for(ll i=a;i>=b;i-=1)
#define ll long long int
#define ld long double
#define pb push_back
#define pf push_front
#define popf pop_front
#define popb pop_back
#define ft first
#define sd second
#define pii pair<int,int>
#define pll pair<long long int, long long int>
#define mysort(a) sort(a.begin(),a.end())
#define myreverse(a) reverse(a.begin(),a.end())
#define mylb(a,val) lower_bound(a.begin(),a.end(),val)
#define myub(a,val) upper_bound(a.begin(),a.end(),val)
#define mem(a,vall) memset(a, vall, sizeof(a))
#define ordered_set tree< pll, null_type,less< pll >, rb_tree_tag,tree_order_statistics_node_update>
/*ll power(ll x, ll y, ll p)
{
    ll res = 1;

    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res*x) % p;
        y = y>>1;
        x = (x*x) % p;
    }
    return res;
}
ll modInverse(ll n, ll p)
{
    return power(n, p-2, p);
}
ll fac[100000+1];
fac[0] = 1;
for (ll i=1 ; i<=100000; i++)
{
    fac[i] = fac[i-1]*i%mod;
}
ll ncr(ll n, ll r, ll p)
{
    if (r==0) return 1;

    return (fac[n]* modInverse(fac[r], p) % p *
            modInverse(fac[n-r], p) % p) % p;
}
ll log(ll a,ll b)
{
    if(a==1)
        return b;
    ll ans = 0;
    while(b)
    {
        ans++;
        b/=a;
    }
    return ans-1;
}*/

int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int test=1;
    //freopen("galactic.in", "r", stdin);    // file open for input
    //freopen("output.txt", "w", stdout);   // file open for output
    //cin>>test;                                 // comment this when number of testcases = 1

    while(test--)
    {

        ll n,m,d,t;
        cin>>n>>m;
        ll arr[n];
        ll ma[n];
        ll arr2[n];
        loop(i,0,n){cin>>arr[i];}
        vector<ll> adj[800000];
        loop(i,0,m)
        {
            cin>>d>>t;
            d--;
            t--;
            adj[d].pb(t);
        }
        ll l=1;
        ll r=800000;
        ll mid,siz,money,tot;

        while(r-l>1)
        {
            mid=(l+r)/2;
            money=0;
            loop(i,0,n){ma[i]=-1;}
            loop(i,0,n){arr2[i]=arr[i];}
            loop(i,0,mid)
            {
                siz=adj[i].size();
                loop(j,0,siz)
                {
                    ma[adj[i][j]]=i;
                }
            }
            loop(i,0,mid)
            {
                money++;
                siz=adj[i].size();
                loop(j,0,siz)
                {
                    if(ma[adj[i][j]]==i)
                    {
                        d=min(arr2[adj[i][j]],money);
                        money-=d;
                        arr2[adj[i][j]]-=d;
                    }
                }
            }
            tot=0;
            loop(i,0,n){tot+=arr2[i];}
            if(money>=2*tot)
            {
                r=mid;
            }
            else
            {
                l=mid;
            }
        }

        mid=l;
        money=0;
        loop(i,0,n){ma[i]=-1;}
        loop(i,0,n){arr2[i]=arr[i];}
        loop(i,0,mid)
        {
            siz=adj[i].size();
            loop(j,0,siz)
            {
                ma[adj[i][j]]=i;
            }
        }
        loop(i,0,mid)
        {
            money++;
            siz=adj[i].size();
            loop(j,0,siz)
            {
                if(ma[adj[i][j]]==i)
                {
                    d=min(arr2[adj[i][j]],money);
                    money-=d;
                    arr2[adj[i][j]]-=d;
                }
            }
        }
        tot=0;
        loop(i,0,n){tot+=arr2[i];}
        if(money>=2*tot)
        {
            cout<<l;
        }
        else
        {
            cout<<r;
        }

    }

    return 0;

}

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 2e5+10;
const int MAX = 1000;

int n, m;
vector<int> k(maxn);
vector<int> sale_in_day[maxn];
int end_sale_of_type[maxn];

int finish(int t, int tol){

	for(int i=1; i<n+1; i++){
		end_sale_of_type[i] = t+1;
	}
	for (int i=1; i<t+1; ++i){
		for(int j=0; j<sale_in_day[i].size(); j++){
			end_sale_of_type[sale_in_day[i][j]] = i;
		}
	}

	int money=0;
	vector<int> need = k;
	for(int i=1; i<min(t+1, MAX+1); i++){
		money++;
		for(int j=0; j<sale_in_day[i].size(); j++){
			if(end_sale_of_type[sale_in_day[i][j]] == i){
				int buy = min(money, need[sale_in_day[i][j]]);
				money -= buy;
				need[sale_in_day[i][j]] -= buy;
				tol -= buy;
			}
		}
	}

	if(t>MAX){

		return MAX+2*tol-money;
	}

	if(money>=2*tol) return 1;
	return 0;
}

int main(){
	int tol=0;
	cin >>n >>m;
	for(int i=1; i<n+1; i++){
		cin >>k[i];
		tol += k[i];
	}
	int d, t;
	for(int i=0; i<m; i++){
		cin >>d >>t;
		sale_in_day[d].push_back(t);
	}

	//binary search
	int l=1, r=MAX;
	int ans=2*MAX;
	while(l<=r){
		int mid = (l+r)/2;
		if(finish(mid, tol)){
			ans = mid;
			r = mid-1;
		}
		else{
			l = mid+1;
		}

	}
    if(ans != 2*MAX) cout <<ans;
	else cout <<finish(MAX+1, tol);

	return 0;
}

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

int total;

bool isOK(int l, vector<int>&need, unordered_map<int,vector<int>>&daySale)
{
    vector<int>bought(need.size(),0);

    int money = l;
    int spent = 0;

    for (int i=l; i>=1; i--)
    {
        if (money>i) money--;

        for (auto item: daySale[i])
        {
            int spend = min(money, need[item]-bought[item]);
            money -= spend;
            bought[item] += spend;
            spent += spend;
        }
    }

    return l-spent >= 2*(total-spent);
}

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

    vector<int>need(n+1);
    for (int i=1; i<=n; i++)
        cin>>need[i];

    unordered_map<int,vector<int>>daySale;
    for (int i=0; i<m; i++)
    {
        int d,t;
        cin>>d>>t;
        daySale[d].push_back(t);
    }

    total = accumulate(need.begin(),need.end(),0);

    int left = 0;
    int right = total*2;

    while (left<right)
    {
        int mid = (right-left)/2+left;
        if (!isOK(mid,need,daySale))
            left = mid+1;
        else
            right = mid;
    }

    cout<<left<<endl;
}

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

int total;

bool isOK(int l, vector<int>&need, unordered_map<int,vector<int>>&daySale)
{
    vector<int>bought(need.size(),0);

    int money = l;
    int spent = 0;

    for (int i=l; i>=1; i--)
    {
        money = min(money,i);

        for (auto item: daySale[i])
        {
            int spend = min(money, need[item]-bought[item]);
            money -= spend;
            bought[item] += spend;
            spent += spend;
        }
    }

    return l-spent >= 2*(total-spent);
}

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

    vector<int>need(n+1);
    for (int i=1; i<=n; i++)
        cin>>need[i];

    unordered_map<int,vector<int>>daySale;
    for (int i=0; i<m; i++)
    {
        int d,t;
        cin>>d>>t;
        daySale[d].push_back(t);
    }

    total = accumulate(need.begin(),need.end(),0);

    int left = 0;
    int right = total*2;

    while (left<right)
    {
        int mid = (right-left)/2+left;
        if (!isOK(mid,need,daySale))
            left = mid+1;
        else
            right = mid;
    }

    cout<<left<<endl;
}

//#define anjn
//      Anjan Agarwala - anjn98

//#define opti
#ifdef opti
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,unroll-loops,fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#endif

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

typedef long long int ll;
typedef unsigned long long int ull;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

ll power(ll x,ll y,ll p){ll r=1; x=x%p; while(y){ if(y&1) r= r*x%p; y=y>>1; x=x*x%p; } return r; }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int csrand(int l=0, int r=1e9){
    uniform_int_distribution<int> uid(l, r);
    return uid(rng);
}

#define PR(x) cout<<#x<<" : "<<x<<"\n";
#define PR1(x,y) cout<<#x<<" : "<<x<<"  |  "<<#y<<" : "<<y<<"\n";
#define PR2(x,y,z) cout<<#x<<" : "<<x<<"  |  "<<#y<<" : "<<y<<"  |  "<<#z<<" : "<<z<<"\n";
#define ED cout<<'\n';

#define IO              ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define FILEIO          freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define all(v)          v.begin(),v.end()
#define endl            '\n'
#define fr1(j,n)        for(int j=0;j<n;j++)
#define fr(n)           for(int i=0;i<n;i++)
#define trav(x,s)       for(auto x:s)
#define PB              push_back
#define pii             pair<int,int>
#define pll             pair<long long int,long long int>
#define F               first
#define S               second
#define binf            2000000000000000001
#define mod             1000000007

const int N=2e5+99 ;
ll mod1=998244353;
vector<ll> a(N),st;
set<ll> off[N];

int main()
{

    IO
    #ifndef ONLINE_JUDGE
    FILEIO
    #endif

	int n,m; cin>>n>>m;
	ll hi=0;
	fr(n) cin>>a[i+1],hi+=a[i]+a[i];
	fr(m)
	{
		int d,t; cin>>d>>t;
		off[t].insert(d);
	}
	ll lo=0,mi,ans=1e9;
	hi=N+N;

	while(lo<=hi)
	{
		ll mi=(lo+hi)/2;
		vector<pll> v;
		//cout<<mi<<" ";
		for(ll i=1;i<=n;i++)
		{
			auto j=off[i].upper_bound(mi);
			if(j==off[i].begin()) continue;
			j--;
			//cout<<*j<<" ";
			v.PB({*j,i});
		}
		sort(all(v));
		st=a; ll cur=0,j=0;

		for(int i=1;i<=mi;i++)
		{
			cur++;
			while(j<v.size() && v[j].F<i)j++;
			while(j<v.size() && v[j].F==i)
			{
				ll ta=min(cur,st[v[j].S]);
				cur-=ta;
				st[v[j].S]-=ta;
				j++;
			}
		}
		ll rem=0;
		fr(n) rem+=st[i+1];
		rem+=rem;

		if(cur>=rem)
			ans=min(ans,mi),hi=mi-1;
		else
			lo=mi+1;

	}
	cout<<ans<<endl;

}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
	ll n,m,i,sum=0,money,mi,x,y,j,bal,Sum;
	cin>>n>>m;
	ll arr[200001],temp[200001],l,k,r,mid;
	vector<ll> offer[200001];
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		sum+=arr[i];
	}
	//sum*=2;
	for(i=0;i<m;i++)
	{
		cin>>x>>y;
		offer[x].push_back(y);
	}
	l=1;
	r=sum*2;
	while(r>=l)
	{
		mid=(l+r)/2;
		for(i=1;i<=n;i++)
			temp[i]=arr[i];
    bal = 2*sum;
    //Sum = sum;
    mi = mid;
		for(j=min(mid,(long long)200000);j>0;j--)
		{
			mi=min(mi,j);
			for(k=0;k<offer[j].size();k++)
			{
				money=min(mi,temp[offer[j][k]]);
				bal -= money;
        //Sum -= money;
				temp[offer[j][k]]-=money;
				mi-=money;
			}
		}
		if(bal<=mid)
		{
			r=mid-1;
		}
		else
			l=mid+1;
	}
	cout<<l<<endl;
	return 0;
}

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#define N 200005
using namespace std;
typedef long long ll;
const ll mod = 998244353LL;
int n, m;
int k[N];
int cnt[N];
bool check(vector<pair<int,int>>& sv, int tot, int ds) {
  map<int, int> mp;
  mp.clear();
  for (int i = 0; i < sv.size(); ++i) {
    int d = sv[i].first;
    int t = sv[i].second;
    if (d <= ds) {
      mp[t] = max(mp[t], d);
    }
  }
  int det=0;
  vector<pair<int, int>> rk;
  rk.clear();
  for (auto itr = mp.begin(); itr != mp.end(); ++itr) {
    rk.push_back(make_pair(itr->second, itr->first));
  }
  // for (int i = 1; i <= n; ++i) {
  //   if (mp.find(i) == mp.end()) det += k[i];
  // }
  sort(rk.begin(), rk.end());
  int cur=0;
  int j = 0;
  for (int i = 1; i <= ds; ++i) {
    cur++;
    int sum=0;
    while(j < rk.size() && rk[j].first == i) {
      sum += k[rk[j].second];
      j++;
    }
    if (cur >= sum) {
      det += sum;
      cur -= sum;
    } else {
      det += cur;
      cur =0;
    }
    if (cur >= (tot-det)*2) {
      return true;
    }
  }
  return cur>=(tot-det)*2;
}
int main() {
  cin>>n>>m;
  int tot=0;
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &k[i]);
    tot += k[i];
  }
  set<pair<int,int>> ss;
  ss.clear();
  for (int i = 1; i <= m; ++i) {
    int d, t;
    scanf("%d%d", &d, &t);
    ss.insert(make_pair(d, t));
  }
  vector<pair<int,int>> sv(ss.begin(), ss.end());
  int l = 1, r = 2*tot;
  while(l<r) {
    int mid=(l+r)/2;
    if (check(sv, tot, mid)) {
      r = mid;
    } else {
      l = mid+1;
    }
  }
  cout<<r<<endl;
  return 0;
}

/*
Solved by sid2104
on 02/06/2020  17:01
*/
#include <bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpii         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
//#define debug(x)    cout<<#x<<" is "<<(x)<<endl;cout.flush();
#define debug(x)    ;
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int)((x).size())
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define elasped_time 1.0 * clock() / CLOCKS_PER_SEC
#define tree        vector<vector<int> >
#define PI          3.14159265358979323846
int inf=99999999999;
const int mod=1e9+7;
const int cmp=1e17;
void inp(int n,int arr[])
{
    f(i,0,n) cin>>arr[i];
}
tree v(2005);
int n,m;
int a[1005];
int sum=0;
int ans=LLONG_MAX;
bool check(int d)
{
    debug(d);
    debug(sum);
    int na[1005];
    f(i,0,1005)
    na[i]=a[i];
    int used=0;
    int save=0;
 for(int i=d;i>0;i--)
 {
     debug(i);

     used=max(used,d-i);
     int now=d-used;
     debug(now);
     for(int el:v[i])
     {
         debug(el);

         if(na[el]&&now)
         {
             debug(na[el]);
             int add=min(na[el],now);
             debug(add);
             na[el]-=add;
             now-=add;
             used+=add;
             save+=add;
             debug(used);
         }

     }

 }
 debug(save);
   debug(endl);
 if(d>=sum-save)
 {
     ans=min(ans,d);
     return true;
 }
 else return false;

}
void solve()
{

    cin>>n>>m;

    f(i,0,n)
    cin>>a[i],sum+=a[i]*2;

    f(i,0,m)
    {
        int a,b;
        cin>>a>>b;
        b--;
        v[a].pb(b);
    }
    int st=1;int en=2000;
    while(st<=en)
    {
        int m=(st+en)/2;
        if(check(m))
        {
            en=m-1;
        }
        else
        {
            st=m+1;
        }

    }
    cout<<ans<<endl;

}
main()
{
    IOS;
    // int t;
    // cin>>t;
    // while(t--)
    solve();

}

/* ****TCIITB**** */

#include<bits/stdc++.h>
#define io          ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll          long long
#define pb          push_back
#define	endl		'\n'
#define pii         pair<ll int,ll int>
#define vi          vector<ll int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define hell        1000000007
#define rep(i,a,b)	for(int i=a;i<b;i++)
#define lbnd        lower_bound
#define ubnd        upper_bound
#define bs          binary_search
#define mp          make_pair
#define time        cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
using namespace std;

#define N  600006
set<ll> adj[N];
std::vector<ll> cost(N);
ll n,m;
ll vis[N];
std::vector<ll> cost1(N);
set<ll> adj1[N];
bool check(ll x)
{
	rep(i,0,N)
	{
		vis[i]=0;
		adj1[i].clear();
	}
	cost1.clear();
	ll s=0;
	rep(i,1,n+1)
	{
		cost1[i]=cost[i];
		s+=2*cost1[i];
	}
	for(ll i=x;i>=1;i--)
	{
		if(adj[i].size()==0)
			continue;
		for(auto j:adj[i])
		{
			if(!vis[j])
			{
				adj1[i].insert(j);
				vis[j]=1;
			}
		}
	}
	ll cb=0;
	rep(i,1,x+1)
	{
		cb++;
		if(adj1[i].size()==0)
			continue;
		for(auto j:adj1[i])
		{
			ll z=min(cost1[j],cb);
			cb-=z;
			cost1[j]-=z;
			s-=2*z;
		}
	}
	if(cb>=s)
		return 1;
	else
		return 0;

}
int main()
{

	io

	cin>>n>>m;

	ll cnt=0;
	rep(i,1,n+1)
	{
		cin>>cost[i];
		cnt+=cost[i];
	}

	rep(i,0,m)
	{
		ll x,y;
		cin>>x>>y;
		adj[x].insert(y);
	}
	ll lo=1,hi=4e5,ans=hell;
	while(lo<=hi)
	{

		ll mid=(lo+hi)/2;
		// cout<<mid<<endl;
		if(check(mid))
		{
			ans=min(ans,mid);
			hi=mid-1;
		}
		else
		{
			lo=mid+1;
		}
	}
	cout<<ans;

}

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

using namespace std;
int n, m;
vector<int> a;
vector<pair<int, int> > b;
bool can(int d1)
{
    vector<int> c(n, -1);
    for(int i = 0; i < m; i++)
    {
        if(b[i].first <= d1) c[b[i].second] = max(c[b[i].second], b[i].first);
    }
    vector<int> d[2005];
    for(int i = 0; i < n; i++)
    {
        if(c[i] != -1) d[c[i]].push_back(i);
    }
    vector<int> e = a;
    int k = 0;
    for(int i = 0; i <= d1; i++)
    {
        k++;
        //cout << i << " : " << d[i].size() << "  ";
        for(int j = 0; j < d[i].size() && k; j++)
        {
            if(k >= e[d[i][j]])
            {
                k -= e[d[i][j]];
                e[d[i][j]] = 0;
            }
            else
            {
                e[d[i][j]] -= k;
                k = 0;
            }
        }
    }
    int l = 0;
    for(int i = 0; i < n; i++) l += e[i];
    return l * 2 <= k;
}
int main()
{
    //ifstream cin("input.txt");
    //ofstream cout("output.txt");

    cin >> n >> m;
    for(int i = 0; i < n; i++)
    {
        int t;
        cin >> t;
        a.push_back(t);
    }
    for(int i = 0; i < m; i++)
    {
        int v1, v2;
        cin >> v1 >> v2;
        b.push_back(make_pair(v1 - 1, v2 - 1));
    }
    int i = 0;
    while(!can(i)) i++;
    cout << i + 1;
    return 0;
}

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

#define fi first
#define se second
#define pb push_back
#define mod(n,k) ( ( ((n) % (k)) + (k) ) % (k))
#define forn(i,a,b) for(int i = a; i < b; i++)
#define forr(i,a,b) for(int i = a; i >= b; i--)
#define all(x) (x).begin(), (x).end()

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

const int maxn = 200000+10;
vi tipos[maxn];
int A[maxn];
int A2[maxn];
ii B[maxn];
int N,M;

bool can(int d){
	forn(i,0,N)A2[i] = A[i];
	unordered_map<int,int> ulti;
	forn(i,0,M){
		ii x = B[i];
		if(x.fi > d)continue;
		ulti[x.se] = max(ulti[x.se],x.fi);
	}
	int m = 0;
	forn(i,1,d+1){
		m++;
		if(i >= maxn){
			continue;
		}
		for(auto &x : tipos[i]){
			if(ulti[x] == i){
				while(A2[x] > 0 && m > 0){
					m--;
					A2[x]--;
				}
			}
		}
	}
	int s = 0;
	forn(i,0,N)s += A2[i];
	if(2*s > m)return false;
	return true;
}
int main(){
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin >> N >> M;
	int sum = 0;
	forn(i,0,N){
		cin >> A[i];
		sum += A[i];
	}
	forn(i,0,M){
		cin >> B[i].fi >> B[i].se; B[i].se--;
		tipos[B[i].fi].pb(B[i].se);
	}
	int ini = 1,fin = 2*sum+1;
	while(ini < fin){
		int mit = (ini+fin)>>1;
		if(can(mit))fin = mit;
		else ini = mit+1;
	}
	cout << ini << '\n';
	return 0;
}
/*
__builtin_mul_overflow(x,y,&x)
-fsplit-stack
*/

#include <bits/stdc++.h>

using namespace std;
#define inf 1000000000
#define unvisited -1
#define visited 1
#define eps 1e-9
#define mp make_pair
#define pb push_back
#define pi acos(-1.0)
#define uint64 unsigned long long
#define FastSlowInput ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;

const int maxn = 2e5 + 5;

vector<vi> AdjList;
int n;
int a[maxn];

bool isValid(int mid) {
	int i,j;
	vector<vi> listPromo;
	int temp[maxn];
	for(i=1;i<=n;i++){
		temp[i] = a[i];
	}
	listPromo.assign(maxn, vi());
	for(i=1;i<=n;i++){
		if(AdjList[i].size() == 0){continue;}
		int idx = lower_bound(AdjList[i].begin(), AdjList[i].end(), mid) - AdjList[i].begin();
		if(idx == AdjList[i].size()){idx--;}
		if(idx < 0){continue;}
		if(AdjList[i][idx] > mid){
			idx--;
		}
		if(idx < 0){continue;}

		listPromo[AdjList[i][idx]].pb(i);
	}
	int burle = 0;
	int day = 1;
	while(day <= mid) {
		burle++;
		for(i=0;i<listPromo[day].size();i++){
			int jenis = listPromo[day][i];
			int biaya = min(temp[jenis], burle);
			temp[jenis] -= biaya;
			burle -= biaya;
		}
		day++;
	}
	for(i=1;i<=n;i++){
		if(temp[i]){
			int biaya = temp[i]*2;
			if(burle < biaya){return false;}
			burle -= biaya;
		}
	}
	return true;
}

int main(){
	int m,i,j;
	scanf("%d %d",&n,&m);

	AdjList.assign(maxn, vi());
	for(i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for(i=0;i<m;i++){
		int d,t;
		scanf("%d %d",&d,&t);
		AdjList[t].pb(d);
	}
	for(i=1;i<=n;i++){
		sort(AdjList[i].begin(), AdjList[i].end());
	}

	int kiri = 1, kanan = 400010, mid, ans;
	while(kiri<=kanan) {
		mid = (kiri+kanan)/2;
		if(isValid(mid)){
			ans = mid;
			kanan = mid-1;
		}else{
			kiri = mid+1;
		}
	}
	printf("%d\n",ans);

	return 0;
};

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

int N,M;
int K[200010],cnt[200010] = {};
int last[200010] = {};
vector<vector<int>> v(400010),u(400010);

int main(){
    cin >> N >> M;
    int sum = 0;
    for(int i=1;i<=N;i++){
        cin >> K[i];
        sum += K[i];
    }
    int d,t;
    for(int i=1;i<=M;i++){
        cin >> d >> t;
        v[t].push_back(d);
    }
    for(int i=1;i<=N;i++) sort(v[i].begin(),v[i].end(),greater<int>());
    int l = 0,r = 2*sum;
    while(l+1<r){
        int m = (l+r)/2;
        int money = 0;
        for(int i=1;i<=m;i++) u[i].clear();
        for(int i=1;i<=N;i++){
            cnt[i] = 0;
            for(auto x:v[i]){
                if(x<=m){
                    u[x].push_back(i);
                    break;
                }
            }
        }
        for(int i=1;i<=m;i++){
            money++;
            for(auto x:u[i]){
                int del = K[x]-cnt[x];
                if(del<=money){
                    cnt[x] += del;
                    money -= del;
                }else{
                    cnt[x] += money;
                    money = 0;
                }
            }
        }
        for(int i=1;i<=N;i++) money -= 2*(K[i]-cnt[i]);
        (money>=0? r:l) = m;
    }
    cout << r << endl;
}

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

using namespace std;
#define MAX 200009
int N, M;
int need[MAX];
int needCopy[MAX];
vector<pair<int, int>> sales;
bool active[MAX];
bool was[MAX];

bool can(int day) {
	int sCnt = upper_bound(sales.begin(), sales.end(), make_pair(day, MAX + 1)) - sales.begin();
	memset(active, 0, sizeof(active));
	memset(was, 0, sizeof(was));
	for (int i = sCnt - 1; i >= 0; i--)
		if (!was[sales[i].second]) {
			active[i] = true;
			was[sales[i].second] = true;
		}
	int money = 0;
	int needAll = 0;
	for (int i = 0; i < N; i++) {
		needCopy[i] = need[i];
		needAll += needCopy[i];
	}

	int sIndex = 0;
	for (int d = 0; d <= day; d++) {
		money++;
		while (sIndex < sCnt && sales[sIndex].first <= d) {
			if (active[sIndex]) {
				int buy = min(needCopy[sales[sIndex].second], money);
				needCopy[sales[sIndex].second] -= buy;
				money -= buy;
				needAll -= buy;
			}
			sIndex++;
		}
	}
	return money >= (needAll * 2);
}

int main() {
	cin >> N >> M;
	memset(need, 0, sizeof(need));
	for (int i = 0; i < N; i++)
		cin >> need[i];
	for (int i = 0; i < M; i++) {
		int d, t;
		cin >> d >> t;
		d--; t--;
		sales.push_back({ d, t });
	}
	sort(sales.begin(), sales.end());
	int res = -1;
	/*int mn = 0;
	int mx = MAX * 2;
	while (mn < mx) {

	}*/

	for (int d = 0; d <= MAX * 2; d++) {
		if (can(d)) {
			res = d + 1;
			break;
		}
	}
	cout << res << "\n";

	return 0;
}

#include <bits/stdc++.h>

using namespace std;

int n, m;
vector<int> k;
vector<pair<int, int>> q(1001);

bool can(int day) {
	vector<int> lst(n, -1);
	for (int i = 0; i < m; ++i) {
		if (q[i].first <= day) {
			lst[q[i].second] = max(lst[q[i].second], q[i].first);
		}
	}
	vector<vector<int>> off(1001);
	for (int i = 0; i < n; ++i) {
		if (lst[i] != -1) {
			off[lst[i]].push_back(i);
		}
	}
	vector<int> need = k;
	int cur_money = 0;
	for (int i = 0; i <= day; ++i) {
		++cur_money;
		if (i > 1000) continue;
		for (auto it : off[i]) {
			if (cur_money >= need[it]) {
				cur_money -= need[it];
				need[it] = 0;
			} else {
				need[it] -= cur_money;
				cur_money = 0;
				break;
			}
		}
	}
	return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}

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

	cin >> n >> m;
	k = vector<int>(n);
	for (int i = 0; i < n; ++i) {
		cin >> k[i];
	}
	for (int i = 0; i < m; ++i) {
		cin >> q[i].first >> q[i].second;
		--q[i].first;
		--q[i].second;
	}

	for (int l = 0; l <= 2000; ++l) {
		if (can(l)) {
			cout << l + 1 << endl;
			return 0;
		}
	}

	assert(false);

	return 0;
}

#include <bits/stdc++.h>
#define int long long
using namespace std;
vector<int> kk;
vector<pair<int, int>> q;
int n, m;
bool ok(int mid) {
	vector<int> lst(n + 1, -1);
	for (int i = 0; i < m; i++) {
	        if (q[i].first <= mid) {
	         	lst[q[i].second] = max(lst[q[i].second], q[i].first);
		}
	}
	vector<vector<int>> what((int)2002);
	for (int i = 1; i <= n; ++i) {
	 	if (lst[i] != -1) {
	 	 	what[lst[i]].push_back(i - 1);
		}
	}
	int ans = 0;
	vector<int> k = kk;
	int burl = 0;
	for (int day = 1; day <= mid; ++day) {
		++burl;
	 	for (auto u : what[day]) {
	 	 	if (burl >= k[u]) {
	 	 	 	burl -= k[u];
				k[u] = 0;
			} else {
			 	k[u] -= burl;
				burl = 0;
				break;
			}
		}
	}
	return accumulate(k.begin(), k.end(), 0LL) * 2 <= burl;
}
signed main() {
	cin >> n >> m;
	kk.resize(n);
	int sum = 0;
	for (int i = 0; i < n; i++) cin >> kk[i], sum += kk[i];
	for (int i = 0; i < m; ++i) {
	 	int d, t;
		cin >> d >> t;
		q.push_back({d, t});
	}
	/*int left = 0, right = 2 * sum + 1;
	while (right - left > 1) {
	 	int mid = (right + left) / 2;
		if (ok(mid)) right = mid;
		else left = mid;
	}
	cout << right; */
	for (int i = 1; i <= 2007; ++i) {
	 	if (ok(i)) return cout << i, 0;
	}
}

#include<bits/stdc++.h>
using namespace std;
const int M=4e5+5;
int n,m,k[M],b[M],ans;

inline void read(int &x)
{
	char ch=getchar();int u=0,f=1;
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch)){u=(u<<1)+(u<<3)+(ch^48);ch=getchar();}x=u*f;
}

struct node
{
	int d,w;
}t[M];

bool cmp(node x,node y){return x.d<y.d;}

bool check(int x)
{
	int q=x,qq=0,tt=0;
	for(int i=1;i<=n;i++)b[i]=k[i];
	for(int i=m;i>=1;i--)if(x>=t[i].d){tt=i;q=t[i].d;break;}
	for(int i=tt;i>=1;i--)
	{
		q=min(q,t[i].d);
		if(b[t[i].w]&&q)
		{
			int xx=min(q,b[t[i].w]);
			qq+=xx;
			q-=xx;
			b[t[i].w]-=xx;
		}
	}
	for(int i=1;i<=n;i++)if(b[i])qq+=b[i]*2;
	if(qq>x)return 0;
	return 1;
}

int main()
{
	read(n),read(m);
	for(int i=1;i<=n;i++)read(k[i]);
	for(int i=1;i<=m;i++)read(t[i].d),read(t[i].w);
	sort(t+1,t+m+1,cmp);
	int l=1,r=400005;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(check(mid))ans=mid,r=mid-1;
		else l=mid+1;
	}
	cout<<ans;
	return 0;
}

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

#define pb push_back
const int MAXN = 2 * 1e5 + 10;

int n, m, k[MAXN], sum = 0;
vector<int> discount[MAXN];

int lastDis[MAXN * 3];
bool check(int d){
	fill(lastDis, lastDis + d + 1, 0);
	for(int i = 1; i <=n; i++){
		if(discount[i].size()==0)continue;
		int l = 0, r = discount[i].size(), m;
		while(r-l > 1){
			m = (l+r)/2;
			if(discount[i][m] <= d)l = m;
			else r = m;
		}
		if(discount[i][l] <= d) lastDis[discount[i][l]] += k[i];
	}

	int money = 0, left = sum;
	for(int i = 1; i <= d; i++){
		money++;
		int take = min(lastDis[i], money);
		money -= take;
		left -= take;
		if(!left) return true;
	}
	if(money >= 2 * left) return true;
	return false;
}

int main(){
	cin>>n>>m;
	for(int i = 1; i <= n; i++){
		cin>>k[i];
		sum += k[i];
	}
	int ti, di;
	for(int i = 0; i < m; i++){
		cin>>di>>ti;
		discount[ti].pb(di);
	}
	for(int i = 1; i <= n; i++){
		sort(discount[i].begin(), discount[i].end());
	}
	int l = sum - 1, r = 2 * sum, m;
	while(l + 1 < r){
		m = (l + r) / 2;
		if(check(m))r = m;
		else l = m;
	}
	cout << r << endl;

	return 0;
}

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
using namespace std;
const int maxn = 4e5+10;

int read(){
	int x=0,f=1;
	char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=(x<<3)+(x<<1)+c-48;c=getchar();}
	return x*f;
}

int k,m,n,num=2e5;
int sum[maxn],S[maxn];
vector<int> a[maxn];
inline bool check(int mid){
	int last=mid,ans=0;
	for(register int i=1;i<=n;i++)sum[i]=S[i];
	for(register int i=mid;i>=1;i--){
		last=min(last,i);
		for(register int j=0;j<a[i].size();j++){
			int x=a[i][j];
			if(last>=sum[x]){last-=sum[x];ans+=sum[x];sum[x]=0;}
			else {sum[x]-=last;ans+=last;last=0;}
		}
	}
	for(register int i=1;i<=n;i++)ans+=sum[i]*2;
	if(ans<=mid)return true;
	return false;
}

int main(){
	n=read();m=read();
	for(register int i=1;i<=n;i++)S[i]=sum[i]=read();
	for(register int i=1;i<=m;i++){
		int x=read(),y=read();
		a[x].push_back(y);
	}/*
	int last=num,ans=0,summ=0;;
	for(register int i=num;i>=1;i--){
		last=min(last,i);
		for(register int j=0;j<a[i].size();j++){
			int x=a[i][j];
			if(last>=sum[x]){last-=sum[x];ans+=sum[x];sum[x]=0;}
			else {sum[x]-=last;ans+=last;last=0;}
		}
	}
	for(register int i=1;i<=n;i++)ans+=sum[i]*2;
	printf("%d\n",ans-summ);*/
	int l=1,r=num*2,ans;
	while(l<=r){
		int mid=(l+r)>>1;
		if(check(mid)){r=mid-1;ans=mid;}
		else l=mid+1;
	}
	printf("%d\n",ans);
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
#define clr(a,x) memset(a,x,sizeof(a))
#define SZ(x) ((int)(x).size())
#define lson rt<<1
#define rson rt<<1|1
#define pb push_back
#define fi first
#define se second
#define what_is(x) cerr<<#x<<" "<<x<<endl;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
template <typename T>
inline void _read(T& x){
    cin>>x;
}
void R(){}
template <typename T,typename... U>
void R(T&head,U&... tail){
    _read(head);
    R(tail...);
}

template <typename T>
inline void _write(const T& x){
    cout<<x<<' ';
}
void W(){cout<<endl;}
template <typename T,typename... U>
void W(const T&head,const U&... tail){
    _write(head);
    W(tail...);
}

void go();
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    go();
    return 0;
}
/****************ackun*********************/
const int MAXN=4e5+100;
int a[MAXN],b[MAXN],lst[MAXN];
vi v[MAXN];
int n,m;
ll sum;
bool check(int mid){
    rep(i,1,2e5+2){
        b[i]=a[i];
        lst[i]=0;
    }
    rep(i,1,mid){
        for(auto x:v[i]){
            lst[x]=i;
        }
    }
//    rep(i,1,n){
//        cout<<"("<<b[i]<<","<<lst[i]<<") ";
//    }
//    cout<<endl;
    int money=0;
    ll cnt=0;
    rep(i,1,mid){
        money++;
        for(auto x:v[i]){
            if(lst[x]==i){
                while(b[x]&&money){
                    money--;
                    cnt++;
                    b[x]--;
                }
            }
        }
    }
    //W(cnt,money,sum);
    return cnt+money/2>=sum;
}
void go(){
    R(n,m);
    rep(i,1,n){
        R(a[i]);
        sum+=a[i];
    }
    rep(i,1,m){
        int x,y;
        R(x,y);
        v[x].pb(y);
    }
    int l=1,r=4e5+10,ans=r;
    //l=r=13;
    while(l<=r){
        //W(l,r);
        int mid=(l+r)>>1;
        if(check(mid)){
            ans=mid;
            r=mid-1;
        }else{
            l=mid+1;
        }
    }
    W(ans);
}

#include <bits/stdc++.h>
using namespace std;
typedef complex<double> cp;
typedef long long ll;
const ll maxn = 2e5+100;
const double pi = acos(-1);

struct Day {
    ll day, w, app_cnt, cnt;
    bool use;
}day[maxn];

ll n, num[maxn], m, sum, Num[maxn];
bool Last_day[maxn];
map <ll, ll> maps;

bool cmp(Day x, Day y) {
    if(x.day != y.day)
        return x.day < y.day;
    else if(x.app_cnt != y.app_cnt)
        return x.app_cnt < y.app_cnt;
    else
        return x.cnt > y.cnt;
}

void init() {
    scanf("%lld%lld", &n, &m);
    for(int i=1;i<=n;i++) {
        scanf("%lld", &num[i]);
        sum += num[i];
    }
    for(int i=1;i<=m;i++){
        scanf("%lld%lld", &day[i].day, &day[i].w);
        maps[day[i].w]++;
    }
    for(int i=1;i<=m;i++) {
        day[i].app_cnt = maps[day[i].w];
        day[i].cnt = num[day[i].w];
    }
    sort(day+1, day+1+m, cmp);
}

bool checke(ll dead_line) {
    for(int i=1;i<=n;i++) Num[i] = num[i];
    ll sp_money = 0, had = 0, Sum = sum, last_day = 0;
    memset(Last_day, 0, sizeof(Last_day));

    for(int i=m;i>=1;i--) {
        day[i].use = false;
        if(day[i].day > dead_line) continue;
        else {
            int w = day[i].w;
            if(!Last_day[w]) {
                day[i].use = true;
                Last_day[w] = true;
            }
        }
    }

    for(int i=1;i<=m;i++) {
        if(!day[i].use) continue;
        ll days = day[i].day;
        ll w = day[i].w;

        if(days > dead_line) break;
        last_day = days;
        had = days - sp_money;

        ll cnt = Num[w];

        if(had >= cnt) {
            Num[w] = 0;
            sp_money += cnt;
            Sum -= cnt;
            had -= cnt;
        } else {
            Num[w] -= had;
            sp_money = days;
            Sum -= had;
            had = 0;
        }
    }
    ll sp_day = Sum*2 - had + last_day;

    return sp_day <= dead_line;
}

int main() {
//    freopen("1.in.txt", "r", stdin);
    init();

    ll l = -1, r = maxn*maxn*10, mid;
    while(r - l > 1) {
        mid = l + r >> 1;
        if(checke(mid)) {
            r = mid;
        } else {
            l = mid;
        }
    }
    printf("%lld\n", r);
    return 0;
}

//#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<math.h>
#include<cmath>
#include<time.h>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
#include<numeric>
#include<stack>
#include<bitset>
//#include<unordered_map>
const int maxn = 0x3f3f3f3f;
const double EI = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354594571382178525166427;
const double PI = 3.141592653589793238462643383279;
//#ifdef TRUETRUE
//#define gets gets_s
//#endif
using namespace std;
int c[1010],cc[1010];
struct s
{
	int a, b;
}z[1010];
struct ss
{
	int z1[1010], z2[1010];
}zz[1010];
vector<int>ve[3010];
int tmp[1010], ttmp;
int v[1010], vv[1010];
inline bool comp(s a, s b)
{
	return a.a < b.a;
}
int main(void)
{
	//ios::sync_with_stdio(false);
	int n, m, i, j, k, sum, pos, qq, cnt, ans,zzz;
	while (~scanf("%d %d", &n, &m))
	{
		cnt = 0;
		sum = 0;
		for (i = 1; i <= n; i++)
		{
			scanf("%d", c + i);
			sum += c[i];
		}
		memcpy(cc,c,sizeof(c));
		for (i = 0; i < m; i++)
		{
			scanf("%d %d", &z[i].a, &z[i].b);
		}
		//printf("22222 %d\n",m);
		sort(z, z + m, comp);
		//printf("33333\n");
		sum *= 2;
		memset(v, 0, sizeof(v));
		//printf("111\n");
		for (i = 0; i < m; i++)
		{
			v[z[i].b] = z[i].a;
			//printf("222\n");
		}
		//printf("666\n");
		for (i = 1; i <= n; i++)
		{
			ve[v[i]].push_back(i);
		}
		ans = maxn;
		//printf("222\n");
		for (int kk = 1;kk <= sum;kk++)
		{
			memcpy(c, cc, sizeof(cc));
			memset(v, 0, sizeof(v));
			//printf("111\n");
			for (i = 0; i < m; i++)
			{
				if (z[i].a > kk)
				{
					continue;
				}
				v[z[i].b] = z[i].a;
				//printf("222\n");
			}
			//printf("666\n");
			for (i = 0; i <= 2010; i++)
			{
				ve[i].clear();
			}
			for (i = 1; i <= n; i++)
			{
				ve[v[i]].push_back(i);
			}
			qq = 0;
			zzz = 0;
			for (i = 1; i <= sum; i++)
			{
				qq++;
				int si = ve[i].size();
				for (j = 0; j < si; j++)
				{
					if (c[ve[i][j]] >= qq)
					{
						//printf("111\n");
						c[ve[i][j]] -= qq;
						zzz += qq;
						qq = 0;
						break;
					}
					else
					{
						//printf("222  %d  %d\n",i, ve[i][j],c[ve[i][j]]);
						qq -= c[ve[i][j]];
						zzz += c[ve[i][j]];
						c[ve[i][j]] = 0;
					}
				}
				ans = min(ans, i + max(((sum / 2 - zzz) * 2 - qq), 0));
				//if(i == 2)
				//printf("ans = %d  %d %d\n",ans,qq,zzz);
				if (zzz == sum / 2)
				{
					break;
				}
				//printf("qq = %d  %d  %d %d\n",qq,si,i,ans);
			}
			ans = min(ans, sum);
		}
		printf("%d\n", ans);
	}
	return 0;
}

/*

1 1
1
3 1

1 0
10

1 1
10
11 1

4 5
1 1 1 1
2 1
2 2
4 1
3 3
3 4

*/

#include <bits/stdc++.h>
#define pb push_back
#define ld long double
#define fi first
#define se second
#define ll long long
#define ss(x) (int) x.size()
#define mp make_pair
#define up(i, n) for(int i = 1; n >= i; ++i)
using namespace std;
const int nax = 200005, mod = 998244353;
const ll inf = 1e18;

int n, m;
ll ile[nax];
vector <ll> v[nax];
ll mam[nax];
ll sum;

bool Fun(ll x)
{
	ll E = sum;
	for(int i = 1; n >= i; ++i)
		mam[i] = ile[i];
	ll wyd = 0;
	ll kasa = x;
	for(int i = min((ll) 200000, x); i >= 1; --i)
	{
		kasa = min(kasa, (ll) i);
		for(auto it: v[i])
		{
			if(mam[it] == 0 || kasa == 0)
				continue;
			int biore = min(kasa, mam[it]);
			mam[it] -= biore;
			E -= biore;
			kasa -= biore;
			wyd += biore;
		}
	}
	if(x - wyd >= 2 * E)
		return 1;
	return 0;
}

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

	cin >> n >> m;
	for(int i = 1; n >= i; ++i)
	{
		cin >> ile[i];
		sum += ile[i];
	}
	for(int i = 1; m >= i; ++i)
	{
		int a, b;
		cin >> a >> b;
		v[a].pb(b);
	}
	ll lewo = 1;
	ll prawo = 1e15;
	while(prawo > lewo)
	{
		ll mid = (lewo + prawo) / 2;
		if(Fun(mid))
			prawo = mid;
		else
			lewo = mid + 1;
	}
	cout << lewo;

    return 0;
}

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

#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define FORE(i, a, b) for(int i = (a); i <= (b); i++)
#define FORD(i, a, b) for(int i = (a); i >= (b); i--)

// Init variables here
const int N = 1e6 + 7;
int n, m;
int k[N];
vector<int> day[N];

void input() {
  //freopen("??.in", "r", stdin);
  //freopen("??.out", "w", stdout);
  scanf("%d %d", &n, &m);
  FORE(i, 1, n) {
    scanf("%d", &k[i]);
  }
  FORE(i, 1, m) {
    int d, t; scanf("%d %d", &d, &t);
    day[d].push_back(t);
  }
}

/*
1165F1 - Microtransactions (easy version)
tag:
Idea: BledDest

Let's iterate over all possible answers. Obviously, this value is always in the range [1,2⋅∑i=1nki]. The first day when Ivan can order all microtransactions he wants will be the answer. How to check if the current day ansd is enough to order everything Ivan wants?

If we had several sale days for some type of microtransaction (of course, we can use only such days that are not greater than the fixed last day ansd), let's use the last one, it is always not worse than some of the previous days. Then let's iterate over all days from 1 to ansd and do the following: firstly, let's increase our balance by one burle. Then let's try to order all microtransactions for which the current day is the last sale day (and pay one burle per copy). If we are out of money at some moment then just say that we should order all microtransactions that remain in this sale day during the last day for two burles per copy. It is true because it does not matter which types will remain because this day is the last sale day for all of these types. So, after all, we had some remaining microtransactions that we cannot buy during sales, and the current balance. And the current day is good if the number of such microtransactions multiplied by two is not greater than the remaining balance.
*/

int need[N];
int last[N];
vector<int> sale[N];

bool ok(int M) {
  FORE(i, 1, n) {
    need[i] = k[i];
    sale[i].clear();
  }
  FORE(i, 1, M) {
    for (int &type : day[i]) {
      last[type] = i;
    }
  }
  FORE(i, 1, n) {
    sale[last[i]].push_back(i);
  }
  int cur = 0;
  FORE(i, 1, M) {
    cur++;
    for (int &type : sale[i]) {
      int buy = min(need[type], cur);
      cur -= buy;
      need[type] -= buy;
    }
  }
  return accumulate(need + 1, need + n + 1, 0) * 2 <= cur;
}

void solve() {
  int L = 1, R = N - 1;
  while (L < R) {
    int M = (L + R) / 2;
    if (ok(M)) {
      R = M;
    } else {
      L = M + 1;
    }
  }
  printf("%d\n", L);
  // read the question correctly (is y a vowel?)
  // look out for SPECIAL CASES (n=1?) and overflow (ll vs int?)
}

int main() {
  //auto beginProgram = chrono::steady_clock::now();

  //int t; cin >> t;
  //while (t--)
  {
    input();
    solve();
  }

  //auto endProgram = chrono::steady_clock::now();

  return 0;
}

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn=2e5+5;
struct node
{
	int num,ddl;
}c[maxn],d[maxn];

int l,r,mid,money,tot,a[maxn],n,m,ans;

bool cmp(node a,node b)
{
	return a.ddl<b.ddl;
}

bool isOK(int k)
{
	memset(d,0,sizeof(d));
	for(int i=1;i<=n;i++)d[i].num=a[i];
	for(int i=1;i<=m;i++)
	{
		if(c[i].ddl>k)break;
		d[c[i].num].ddl=c[i].ddl;
	}
	sort(d,d+n+1,cmp);
	int money=0,p=tot;
	for(int i=1;i<=n;i++)
	{
		if(d[i].ddl>k)break;
		money+=d[i].ddl-d[i-1].ddl;
		int w=min(money,d[i].num);
		p-=w;
		money-=w;
	}
	if(p<=k)return true;
	else return false;
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		ans+=2*a[i];
	}
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d",&c[i].ddl,&c[i].num);
	}

	sort(c+1,c+m+1,cmp);
	l=1;r=ans;tot=ans;
	while(l<=r)
	{
		mid=(l+r)>>1;
		if(isOK(mid))ans=mid,r=mid-1;
		else l=mid+1;
	}
	printf("%d\n",ans);
	return 0;
}

#include<bits/stdc++.h>

#define  pf                  printf
#define  sc                  scanf
#define  PI                  2*acos(0.0)
#define  fast                ios_base::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define  mem(a,b)            memset(a, b, sizeof(a) )
#define  gcd(a,b)            __gcd(a,b)
#define  lcm(a,b)            (a*(b/gcd(a,b)))
#define  MAX                 1234567899
#define  mod                 1000000007
#define  all(v)              (v).begin(),(v).end()
#define  vSort(v)            sort(all(v))
#define  maxSort(v)          sort(all(v),greater<int>())
#define  Unique(v)           v.erase(unique(all(v)),v.end())
#define  sqr(x)              ((x)*(x))
#define  qube(x)             ((x)*(x)*(x))
#define  deci(n)             cout<<fixed<<setprecision(n)
#define  sci(n)              sc("%d",&(n))
#define  scii(x,y)           sc("%d %d",&(x),&(y))
#define  scl(x)              sc("%lld",&(x))
#define  scll(x,y)           sc("%lld %lld",&(x),&(y))
#define  vi                  vector<int>
#define  hi                  pf(" HI \n")
#define  pp                  pair<int,int>
#define  pb(x)               push_back(x)
#define  mp(x,y)             make_pair(x,y)
#define  F                   first
#define  S                   second
#define  check(n,pos)        (n & (1<<(pos)))
#define  biton(n,pos)        (n  (1<<(pos)))
#define  bitoff(n,pos)       (n & ~(1<<(pos)))
typedef  long long int       lli;
typedef  unsigned long long int ulli;
int dx4[] = { 0 , 0 , -1 , 1 } ;
int dy4[] = { -1 , 1 , 0 , 0 } ;
bool valid( int r , int c , int x , int y ){
    if( x >= 1 && x <= r && y >= 1 && y <= c ) return 1 ; return 0 ;}

using namespace std;
lli a[1000005];
lli n,m;
lli tot;
lli b[200005];
vector<lli> val[500005];
lli BS(lli mid)
{
    lli taka;
    lli on=0;
    for(int i=1;i<=n;i++)
        b[i]=a[i];
    taka = mid;
    for(lli i=mid;i>=1;i--)
    {
        if(val[i].size()==0)
        {
            if(taka>=i)
                taka--;
            continue;
        }
        for(int j=0;j<val[i].size();j++)
        {
            lli p = min(taka,b[val[i][j]]);
            taka-=p;
            on+=p;
            b[val[i][j]]-=p;
        }
        if(taka>=i)
            taka--;
    }
    return ((tot-on)*2LL)+(on);
}

int main ()
{
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        cin >> a[i];
        tot+=a[i];}
    lli x,y;
    for(int i=1;i<=m;i++)
    {
        cin>> x >> y;
        val[x].pb(y);
    }
//    for(int i=1;i<=200001;i++){
//
//        maxSort(val[i]);
//    }
    lli low = 0;
    lli mid;
    lli high= 2*tot;
    lli ans=0;
    while(low<=high)
    {
        mid = ((high-low)/2)+low;
        if(BS(mid)<=mid)
        {
            ans = mid;
            high= mid-1;
        }
        else
            low= mid+1;
    }
    cout << ans <<endl;

    return 0;
}

/*

5 6

1 2 3 4 5
1 2 0 2 0
0 2 0 2 0 - 1
0 2 0 1 0 - 2
		1 - 3
		2 - 4
		3 - 5
		4 - 6
		5 - 7
		6 - 8

2 4
3 3
1 5
1 2
1 5
2 3

1 2 0 2

1 - 2 5
2 - 3 4
3 - 3

*/

#include<bits/stdc++.h>
#define se second
#define fi first
#define pb push_back
#define rep(i,a,b) for(int i = a; i < b; i++)
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()

#define _ ios::sync_with_stdio(0); cin.tie(0);

#define vi vector<int>
#define ii pair<int,int>
#define vii vector<ii>
#define ll long long
#define vll vector<ll>

const int INF = 1e8;
const int tam = 5 * 1e5;

using namespace std;

vii allof;
int total, n, m;
vi of[tam];
int aux[tam];
int mi[tam];
int maxi[tam];

bool can(int days){
	rep(i,1, n + 1)
		maxi[i] = -1;

	rep(i,0,allof.size())
		if(allof[i].fi <= days && maxi[ allof[i].se ] < allof[i].fi)
				maxi[ allof[i].se ] = allof[i].fi;

	rep(i,1, n + 1)
		if(maxi[i] != -1)
			of[maxi[i]].pb(i);

	rep(i,1, n + 1)
		sort(all(of[i]));

	rep(i, 1, n + 1)
		aux[i] = mi[i];

	int curr = 0;
	int ready = 0;

	rep(i, 1, days + 1){
		curr++;
		int j = 0;
		while(j < of[i].size() && curr){
			if(aux[of[i][j]] > 0){
				aux[of[i][j]]--;
				curr--;
				ready++;
			}else j++;
		}
	}

	rep(i,1, n + 1)
		if(maxi[i] != -1)
			of[maxi[i]].clear();

	return curr >= (total - ready) * 2;
}

int main(){
	_

	int a, b;

	cin>>n>>m;

	rep(i,1,n + 1){
		cin>>mi[i];
		total += mi[i];
	}

	rep(i,1,m + 1){
		cin>>a>>b;
		allof.pb(ii(a,b));
	}

	int ini = 1, fin = 5 * 1e5 - 100;

	while(ini <= fin){
		int mid = (ini + fin)/2;

		if(can(mid)) fin = mid - 1;
		else ini = mid + 1;
	}

	cout<<fin + 1<<"\n";

	return 0;
}

/*input
5 6
1 2 0 2 0
2 4
3 3
1 5
1 2
1 5
2 3

*/

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll , ll> PLL;
typedef long double ld;

#define pb push_back
#define all(c) c.begin(),c.end()
#define allr(c) c.rbegin(),c.rend()
int mod = 998244353;
#define PI 3.14159265
#define endl '\n'
#define debug(x) cout << #x << " = " << x << endl;
#define TRACE

#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

template < typename T > T GCD(T a, T b)            { ll t; while(a) { t = a; a = b % a; b = t; } return b; }
template < typename T > string toString(T a)       { return to_string(a); }
template < typename T > void toInt(string s, T &x) { stringstream str(s); str >> x;}
inline int add(int x, int y){ x += y; if(x >= mod) x -= mod; return x;}
inline int sub(int x, int y){ x -= y; if(x < 0) x += mod; return x;}
inline int mul(int x, int y){ return (x * 1ll * y) % mod;}
inline int powr(int a, ll b){
    int x = 1 % mod;
    while(b){
        if(b & 1) x = mul(x, a);
        a = mul(a, a);
        b >>= 1;
    }
    return x;
}
inline int inv(int a){ return powr(a, mod - 2);}

int n, m;
const int MAX = 400010;
vector <int> vec;
vector <int> off[MAX];

bool isItPossible(int day) {
  int cur = 0;
  int req = accumulate(all(vec), 0);
  vector <int> temp = vec;
  vector <int> toff[MAX];
  vector <bool> vis(n + 1, false);
  for (int i = day; i >= 1; i--) {
    for (auto it : off[i]) {
      if (vis[it]) continue;
      vis[it] = true;
      toff[i].pb(it);
    }
  }
  for (int i = 1; i <= day; i++) {
    cur++;
    if (req * 2 <= cur) {
      return true;
    }
    if (i > 200000) continue;
    for (auto it : toff[i]) {
      int m = min(temp[it], cur);
      cur -= m;
      req -= m;
      temp[it] -= m;
    }
    if (req * 2 <= cur) {
      return true;
    }
  }
  return false;
}

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  cin >> n >> m;
  vec.pb(0);
  int v;
  for (int i = 0; i < n; i++) {
    cin >> v;
    vec.pb(v);
  }
  int d, t;
  for (int i = 0; i < m; i++) {
    cin >> d >> t;
    off[d].pb(t);
  }

  int ans = 0;
  int low = 1, high = 4e5 + 1;
  while (low < high) {
    int mid = (low + high) / 2;
    if (isItPossible(mid)) {
      ans = mid;
      high = mid;
    }
    else {
      low = mid + 1;
    }
  }

  cout << ans << endl;

  return 0;
}

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int n,m;
const int nax=2e5+5;
int ile[nax];
vector<int> offers[nax];
vector<int> dni[nax*2];

bool czy(int x)
{
    for(int i=0;i<2*nax;i++) dni[i].clear();
    vector<int> oferty(nax,-1);
    for(int i=1;i<=n;i++)
    {
        for(int j=0;j<offers[i].size();j++)
        {
            int dzien=offers[i][j];
            if((dzien<=x && dzien>oferty[i]))
            {
                oferty[i]=dzien;
            }
        }
    }
    int potrzeba[nax];
    for(int i=1;i<=n;i++) potrzeba[i]=ile[i];
    for(int i=1;i<=n;i++)
    {
        if(oferty[i]!=-1)
        {
            dni[oferty[i]].push_back(i);
        }
    }
    int stan=0;
    for(int i=1;i<=x;i++)
    {
        stan++;
        for(int j=0;j<dni[i].size();j++)
        {
            int t=dni[i][j];
            if(potrzeba[t]>0)
            {
                int iletrzeba=potrzeba[t];
                int ilemozna=stan;
                potrzeba[t]-=min(iletrzeba,ilemozna);
                stan-=min(iletrzeba,ilemozna);
            }
        }
    }
    int sum=0;
    for(int i=1;i<=n;i++)
    {
        sum+=potrzeba[i];
    }
    if(sum*2<=stan) return true;
    return false;
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>ile[i];
    for(int i=1;i<=m;i++)
    {
        int d,t; cin>>d>>t;
        offers[t].push_back(d);
    }
    int lo=1;
    int hi=2*nax-1;
    while(lo+1<hi)
    {
        int mid=(lo+hi)/2;
        if(czy(mid)) hi=mid;
        else lo=mid;
    }
    if(czy(lo)) cout<<lo;
    else cout<<hi;

    return 0;
}

#include <bits/stdc++.h>
#include <iomanip>

//primes for hashing 937,991,1013,1409,1741

#define FAST std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define DECIMAL(n)  std::cout << std::fixed;std::cout << std::setprecision(n);
#define hell 1000000007
#define PI 3.14159265358979323844
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define endl "\n"
#define maxc(v) max_element(all(v))
#define minc(v) min_element(all(v))
#define GCD(m,n) __gcd(m,n)
#define LCM(m,n) m*(n/GCD(m,n))
#define inputarr(a,n) for(int i=0;i<n;++i) cin>>a[i]
#define initarr(a,n,x) for (int i=0;i<n;++i) a[i]=x
#define rep(i, n)    for(int i = 0; i < (n); ++i)
#define repA(i, a, n)  for(int i = a; i <= (n); ++i)
#define repD(i, a, n)  for(int i = a; i >= (n); --i)
#define trav(a, x) for(auto& a : x)
#define sz(a) (int)a.size()
#define sl(a) (int)a.length()
#define invect(data,n,commands) for(int i = 0;i<n;i++){int tmp;cin>>tmp;data.pb(tmp);commands}
#define inset(data,n,commands) for(int i = 0;i<n;i++){int tmp;cin>>tmp;data.insert(tmp);commands}
#define display(x) trav(a,x) cout<<a<<" ";cout<<endl

#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    std::cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');std::cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}

#define ll long long
#define ld long double
#define pii std::pair<int, int>
#define pll std::pair<ll, ll>
#define vi vector<int>
#define vvi vector<vi >
#define vii vector<pii >

pii operator+(pii a, pii b)
{
    return {a.fi+b.fi,a.se+b.se};
}
pll operator+(pll a, pll b)
{
    return {a.fi+b.fi,a.se+b.se};
}
std::ostream& operator<<(std::ostream& out,pii a)
{
    out<<a.fi<<" "<<a.se<<endl;
    return out;
}
std::ostream& operator<<(std::ostream& out,pll a)
{
    out<<a.fi<<" "<<a.se<<endl;
    return out;
}
std::istream& operator>>(std::istream& in,pii &a)
{
    in>>a.fi>>a.se;
    return in;
}
std::istream& operator>>(std::istream& in,pll &a)
{
    in>>a.fi>>a.se;
    return in;
}

using namespace std;
bool check(int k[],int n,pii off[],int m,int ans)
{
    int newk[n];
    for (int i = 0; i < n; ++i)
    {
        newk[i]=k[i];
    }
    int cnt=0;
    int last=0;
    int first=0;
    int ext=0;
    int flag=0;
    for (int i = m-1; i >=0; --i)
    {
        if(off[i].fi<=ans)
        {
            if(newk[off[i].se]>0)
            {
                last=max(last,off[i].fi);
                if(flag!=0)
                    cnt=cnt+off[i].fi-first;
                if(cnt<0)
                    ext+=(-cnt),cnt=0;
                first=off[i].fi;
                if(off[i].fi>=cnt+newk[off[i].se])
                {
                    cnt+=newk[off[i].se];
                    newk[off[i].se]=0;
                }else{
                    int xxx=off[i].fi-cnt;
                    newk[off[i].se]-=xxx;
                    cnt+=xxx;
                    break;
                }
                flag=1;
            }
        }
    }
    ll sum=0;
    for (int i = 0; i < n; ++i)
    {
        sum+=newk[i]*2;
    }
    sum=max(0ll,sum-(first-cnt)-ext);
    ll days=sum+last;
    if(days<=ans)
        return 1;
    return 0;
}
int main()
{
    FAST;
    int n,m;
    cin>>n>>m;
    int k[n];
    inputarr(k,n);
    pii off[m];
    for (int i = 0; i < m; ++i)
    {
        int d,t;
        cin>>d>>t;
        off[i]=mp(d,t-1);
    }
    sort(off,off+m);
    int high=4*100005;
    int low=1;
    while(high-low>1)
    {
        int mid=low+(high-low)/2;
        if(check(k,n,off,m,mid))
        {
            high=mid;
        }else low=mid+1;
    }
    if(check(k,n,off,m,low))
        cout<<low<<endl;
    else cout<<high<<endl;
}

#include <bits/stdc++.h>
#define fst first
#define snd second
#define fore(i,a,b) for(int i=a,ThxDem=b;i<ThxDem;++i)
#define pb push_back
#define ALL(s) s.begin(),s.end()
#define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define SZ(n) ((int)(n).size())
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;

int mx[500010],n,m,am[500010],rem[500010];
vector<int> lst[500010];
vector<ii> of;

bool can(int d){
  memset(mx,-1,sizeof(mx));
  fore(i,0,n) rem[i]=am[i];
  for(auto x:of) if(x.fst<=d) mx[x.snd]=max(mx[x.snd],x.fst);
  fore(i,0,n) if(mx[i]>=0) lst[mx[i]].pb(i);
  int have=0;
  fore(i,1,d+1){
    have++;
    for(auto x:lst[i]){
      int v=min(rem[x],have);
      have-=v;
      rem[x]-=v;
    }
  }
  fore(i,0,n) have-=2*rem[i];
  return have>=0;
}

int main(){FIN;
  cin >> n >> m;
  fore(i,0,n) cin >> am[i];
  fore(i,0,m){
    int x,y; cin >> x >> y; //mx[y]=max(mx[y],x);
    of.pb({x,y-1});
  }
  int l=1,r=4e5+10;
  while(l<=r){
    int mid=(l+r)/2;
    if(can(mid)) r=mid-1;
    else l=mid+1;
  }
  while(!can(l)) l--;
  cout << l << endl;
}

#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define DEBUG 0

using namespace std;

const long long VERY_LARGE = 10000000000;

pair<long long, long long> V[200000];
pair<long long, long long> VV[200000];
long long K[200001];
long long KK[200001];
long long last_day[200001];

int
main(void)
{
    int i, j, k, n, day;
    int N, M;
    long long KS;
    long long rem;
    long long D, T;
    long long burle;
    long long low, hig, mid;

    cin >> N >> M;

    KS = 0;
    for(j=1;j<=N;j++) {
        cin >> K[j];
        KS += K[j];
    }
    for(j=0;j<M;j++) {
        cin >> D >> T;
        V[j] = make_pair(D, T);
    }
    sort(&V[0], &V[M]);

    low = 0;
    hig = KS*2;
    while (true) {
        mid = (low+hig)/2;
//         cout << "mid=" << mid << endl;
        if ((mid == hig) || (mid == low)) {
            break;
        }
        for(j=1;j<=N;j++) {
            KK[j] = K[j];
        }
        for(j=1;j<=N;j++) {
            last_day[j] = VERY_LARGE;
        }

        for(j=0;j<M;j++) {
            if (V[j].first > mid)
                break;
//             cout << V[j].second << endl;
            last_day[V[j].second] = min(last_day[V[j].second], V[j].first);
        }

        n = 0;
        for(j=1;j<=N;j++) {
            if (last_day[j] < VERY_LARGE) {
//                 cout << "j=" << j << endl;
                VV[n].first = last_day[j];
                VV[n].second = j;
                n++;
            }
        }
//         cout << "n=" << n << endl;
        sort(&VV[0], &VV[n]);

//         for(j=0;j<n;j++) {
//             cout << VV[j].first << "," << VV[j].second << endl;
//         }
        long long buy = 0;
        long long day;
        day = 0;
        for(j=0;j<n;j++) {
            if (KK[VV[j].second]) {
                if ((buy + KK[VV[j].second]) <= VV[j].first) {
//                     cout << "buy " << VV[j].second << " " << KK[VV[j].second] << " times on day " << VV[j].first << endl;
                    buy += KK[VV[j].second];
                    KK[VV[j].second] = 0;
                } else {
//                     cout << "buy " << VV[j].second << " " << (VV[j].first - buy) << " times on day " << VV[j].first << endl;
                    KK[VV[j].second] -= (VV[j].first - buy);
                    buy += (VV[j].first-buy);
                }
            }
        }
//         cout << "rem=" << rem << " on day " << day << endl;
//         cout << "fin on " << (day + rem*2) << " while mid=" << mid << endl;

//         cout << "buy= " << buy << endl;

        if ((buy + (KS-buy)*2) <= mid) {
            hig = mid;
        } else {
            low = mid;
        }
    }

    cout << hig << endl;

    return 0;
}

//      ——By DD_BOND

//#include<bits/stdc++.h>
#include<functional>
#include<algorithm>
#include<iostream>
#include<sstream>
#include<iomanip>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<cstddef>
#include<cstdio>
#include<memory>
#include<vector>
#include<cctype>
#include<string>
#include<random>
#include<cmath>
#include<queue>
#include<deque>
#include<ctime>
#include<stack>
#include<map>
#include<set>

#define fi first
#define se second
#define MP make_pair
#define pb push_back
#define INF 0x3f3f3f3f
#define pi 3.1415926535898
#define lowbit(a)  (a&(-a))
#define lson l,(l+r)/2,rt<<1
#define rson (l+r)/2+1,r,rt<<1|1
#define Min(a,b,c)  min(a,min(b,c))
#define Max(a,b,c)  max(a,max(b,c))
#define debug(x)  cerr<<#x<<"="<<x<<"\n";

using namespace std;

typedef long long ll;
typedef pair<int,int> P;
typedef pair<ll,ll> Pll;
typedef unsigned long long ull;

const int seed=131;
const ll LLMAX=2e18;
const int MOD=1e9+7;
const double eps=1e-8;
const int MAXN=1e6+10;
const int hmod1=0x48E2DCE7;
const int hmod2=0x60000005;

inline ll sqr(ll x){ return x*x; }
inline int sqr(int x){ return x*x; }
inline double sqr(double x){ return x*x; }
ll gcd(ll a,ll b){ return b==0? a: gcd(b,a%b); }
ll exgcd(ll a,ll b,ll &x,ll &y){ ll d; (b==0? (x=1,y=0,d=a): (d=exgcd(b,a%b,y,x),y-=a/b*x)); return d; }
ll qpow(ll a,ll n){ll sum=1;while(n){if(n&1)sum=sum*a%MOD;a=a*a%MOD;n>>=1;}return sum;}
inline int dcmp(double x){  if(fabs(x)<eps) return 0;   return (x>0? 1: -1); }

int num[MAXN],now[MAXN];
vector<int>sale[MAXN];

int main(void)
{
    ios::sync_with_stdio(false);    cin.tie(0);   cout.tie(0);
    // freopen("/My_Mac/Resource/Project__C++/testdata.in","r",stdin);
    //freopen("/My_Mac/Resource/Project__C++/testdata.out","w",stdout);
    int n,m,ans;  cin>>n>>m;
    for(int i=1;i<=n;i++)    cin>>num[i];
    for(int i=1;i<=m;i++){
        int d,t;    cin>>d>>t;
        sale[d].pb(t);
    }
    int l=0,r=1e6;
    while(l<=r){
        int mid=(l+r)>>1,pack=0;
        for(int i=1;i<=n;i++)   now[i]=num[i];
        for(int i=1;i<=mid;i++){
            pack++;
            for(int j=0;j<sale[i].size();j++)
                while(pack&&now[sale[i][j]]){
                    pack--;
                    now[sale[i][j]]--;
                }
        }
        for(int i=1;i<=n;i++)
            while(now[i]){
                now[i]--;
                pack-=2;
            }
        if(pack<0)  l=mid+1;
        else r=mid-1,ans=mid;
    }
    cout<<ans<<endl;
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

int last[1005];
int a[1005];
int g[1005];
int dp[1005][1005];

main(){
    //freopen("input.txt", "r", stdin);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, m, d, t, sum = 0;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i){
        cin >> a[i];
        sum += a[i];
    }
    for (int i = 1; i <= m; ++i){
        cin >> d >> t;
        last[t] = max(last[t], d);
    }
    for (int i = 1; i <= n; ++i) g[last[i]] += a[i];
    dp[1][1] = 1;
    for (int i = 1; i <= 1001; ++i){
        for (int k = 0; k <= g[i]; ++k){
            for (int j = k; j <= i; ++j){
                dp[i + 1][j - k + 1] = max(dp[i + 1][j - k + 1], dp[i][j]);
            }
        }
    }
    int ans = 2 * sum;
    for (int i = 1; i <= 1001; ++i){
        for (int j = 0; j <= 1001; ++j){
            if (dp[i][j] == 1){
                int can = sum - (i - j);
                ans = min(ans, i + 2 * can - 1);
            }
        }
    }
    cout << ans << '\n';
    return 0;
}

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>
#include <bitset>
#include <complex>

using namespace std;

//1165

#define int long long

const int INF = 1e6 + 239;

signed main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int n, m;
	cin >> n >> m;
	vector<int> k(n);
	for (auto &t : k) {
		cin >> t;
	}
	vector<pair<int, int>> p(m);
	for (auto &t : p) {
		cin >> t.first >> t.second;
		t.second--;
	}
	vector<int> in(n, -1);
	for (auto &t : p) {
		in[t.second] = max(in[t.second], t.first);
	}
	vector<pair<int, int>> ef;
	for (int i = 0; i < n; i++) {
		if (in[i] != -1) {
			ef.push_back({in[i], i});
		}
	}
	sort(ef.begin(), ef.end());
	auto ch = [&](int d) {
		vector<int> left = k;
		int alr = 0;
		for (auto t : ef) {
			if (t.first <= d) {
				int can = min(t.first - alr, left[t.second]);
				left[t.second] -= can;
				alr += can;
			} else {
				break;
			}
		}
		int cnt_need = 0;
		for (auto t : k) {
			cnt_need += 2 * t;
		}
		cnt_need -= alr;
		if (cnt_need <= d) {
			return true;
		} else {
			return false;
		}
	};
	int l = 0;
	int r = INF;
	while (r - l > 1) {
		int mid = (r + l) >> 1;
		if (ch(mid)) {
			r = mid;
		} else {
			l = mid;
		}
	}
	cout << r << endl;
	//cout << ch(100) << endl;
}

#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define mod 1000000007
#define fi first
#define se second
#define pb push_back
#define IOS ios_base::sync_with_stdio(false);cout.tie(NULL);cin.tie(NULL);

using namespace std;

int n,m;
vector<int> k(1001);
vector<pair<int,int> > p;

bool f(int x)
{
    vector<int> t=k;
    // for(auto i:t)
    // {
    //     cout<<i<<" ";
    // }
    // cout<<endl;
    vector<int> l(1001,-1);
    for(int i=0;i<m;i++)
    {
        l[p[i].se]=max(l[p[i].se],p[i].fi);
    }
    // for(int i=1;i<=n;i++)
    // {
    //     cout<<l[i]<<" ";
    // }
    // cout<<endl;
    set<int> d;
    vector<int> v[1001];
    for(int i=1;i<=n;i++)
    {
        if(l[i]!=-1)
        {
            d.insert(l[i]);
            v[l[i]].pb(i);
        }
    }
    // for(auto i:d)
    // {
    //     cout<<"dd"<<i<<endl;
    //     for(auto j:v[i])
    //     {
    //         cout<<j<<" ";
    //     }
    //     cout<<endl;
    // }
    int c=0,dd=0;
    for(auto i:d)
    {
        if(i>x) break;
        c+=i-dd;
        //cout<<"bef "<<c<<endl;
        dd=i;
        for(auto j:v[i])
        {
            //cout<<"tup "<<i<<" "<<j<<" "<<t[j]<<endl;
            if(c>=t[j])
            {
                c-=t[j];
                t[j]=0;
            }
            else{
                t[j]-=c;
                c=0;
                break;
            }
        }
        //cout<<"af "<<c<<endl;
    }
    c+=x-dd;
    //cout<<c<<endl;
    return accumulate(t.begin(),t.end(),0)*2<=c;
}

int main()
{
    IOS;
    cin>>n>>m;
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        cin>>k[i];
    }
    int x,y;
    for(int i=0;i<m;i++)
    {
        cin>>x>>y;
        p.pb({x,y});
    }
    int s=accumulate(k.begin(),k.end(),0)*2;
    //cout<<s<<endl;
    for(int i=1;i<=s;i++)
    {
        if(f(i))
        {
            ans=i;
            break;
        }
    }
    cout<<ans<<endl;
    return 0;
}

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=10000+10;

int n, k;
int tol_need = 0;
int tol_money = 0;
int need[maxn];
vector<int> sale_on_day[maxn];

bool finish_in_today(int day){
	for(int i=0; i<sale_on_day[day].size(); i++){
		if(need[sale_on_day[day][i]]){
			int maxBuy = min(need[sale_on_day[day][i]], tol_money);
			need[sale_on_day[day][i]] -= maxBuy;
			tol_need -= maxBuy;
			tol_money -= maxBuy;
		}
		if(!tol_need) return true;
		if(!tol_money) break;
	}

	return tol_money>=tol_need*2;
}

int main(){
	ios::sync_with_stdio(false);
	int m;
	cin >>n >>m;
	for(int i=1; i<=n; i++) {
		cin >>need[i];
		tol_need += need[i];
	}

	int d, t;
	for(int i=0; i<m; i++){
		cin >>d >>t;
		sale_on_day[d].push_back(t);
	}

	int day_now = 0;
	while(tol_need>0){
		tol_money ++; // inc every day
		day_now ++; // date today
		if(finish_in_today(day_now)){
			cout <<day_now;
			break;
		}
	}

	return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define mod 1000000007
#define fi first
#define se second

using namespace std;

int main()
{
    int n,m;
    cin>>n>>m;
    int t[n+1];
    for(int i=1;i<=n;i++)
    {
        cin>>t[i];
    }
    pair<int,int> p[m];
    for(int i=0;i<m;i++)
    {
        cin>>p[i].fi>>p[i].se;
    }
    int ans=0,c=0;
    while(true)
    {
        ans++;
        c++;
        bool f=false;
        for(int i=0;i<m;i++)
        {
            if(p[i].fi==ans && t[p[i].se])
            {
                f=true;
                int tmp=min(t[p[i].se],c);
                t[p[i].se]-=tmp;
                c-=tmp;
                //cout<<ans<<endl;
                break;
            }
        }
        if(f) continue;
        for(int i=1;i<=n;i++)
        {
            if(t[i])
            {
                f=true;
                if(c<2) break;
                t[i]--;
                c-=2;
                //cout<<ans<<endl;
                break;
            }
        }
        if(!f) break;
    }
    cout<<ans-1<<endl;
    return 0;
}

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

const int maxn = 1010;
int n,m,sum;
int k[maxn],maxd[maxn];
vector<int>vt[2020];

struct NODE
{
    int d,t;
}node[maxn];

bool ok(int x)
{
    int money = 0;
    int need[maxn];
    for(int i = 1;i <= n;i++)  need[i] = k[i];

    for(int i = 1;i <= x;i++)
    {
        money++;
        if(i > 1000)  continue;
        for(int j = 0;j < (int)vt[i].size();j++)
        {
            int cnt = vt[i][j];
            if(money >= need[cnt])
            {
                money -= need[cnt];
                need[cnt] = 0;
            }
            else
            {
                need[cnt] -= money;
                money = 0;
                break;
            }
        }
    }

    int c1 = 0;
    for(int i = 1;i <= n;i++)  c1 += need[i];
    return c1 * 2 <= money;
}

int main()
{
    scanf("%d %d",&n,&m);
    for(int i = 1;i <= n;i++)  scanf("%d",&k[i]),sum += k[i];
    for(int i = 1;i <= m;i++)  scanf("%d %d",&node[i].d,&node[i].t);
    for(int i = 1;i <= m;i++)  maxd[node[i].t] = max(maxd[node[i].t],node[i].d);
    for(int i = 1;i <= n;i++)  if(maxd[i])  vt[maxd[i]].push_back(i);

    /*for(int i = 1;i <= n;i++)
    {
        printf("%d: ",i);
        for(int j = 0;j < (int)vt[i].size();j++)  printf("%d ",vt[i][j]);
        printf("\n");
    }*/

    for(int i = 1;i <= 2000;i++)
    {
        if(ok(i))
        {
            printf("%d",i);
            break;
        }
    }

    /*int ans;
    int l = 1,r = 2000,mid;
    while(l <= r)
    {
        mid = (l + r) / 2;
        if(ok(mid))
        {
            ans = mid;
            r = mid - 1;
        }
        else  l = mid + 1;
    }
    printf("%d\n",ans);*/

    return 0;
}

#include<bits/stdc++.h>
#define forn(i,n) for(int (i)=0;(i)<(n);(i)++)
#define pt pair<int,int>
#define all(x) (x).begin(),(x).end()
#define INF 1e10
#define vint vector<int>
#define pb push_back
#define mp make_pair
using namespace std;
typedef  long long ll;
int n,m;
vint k;
vector<pt> q(200001);
bool can(ll ans)
{
	vint lst(n,-1);
	for(auto it:q)
	{
		if(it.first<=ans)
		{
			lst[it.second]=max(lst[it.second],it.first);
		}
	}
	vector<vint> off(200001);
	forn(i,n)
	{
		if(lst[i]!=-1)
		off[lst[i]].pb(i);
	}
	int curr=0;
	vint need=k;
	forn(i,ans+1)
	{
		curr++;
		if(i>200000)
		continue;
		for(auto it:off[i])
		{
			if(need[it]<=curr)
			{
				curr-=need[it];
				need[it]=0;
			}
			else
			{
				need[it]-=curr;
				curr=0;
				break;
			}
		}
	}
	return (2*accumulate(need.begin(),need.end(),0)<=curr);
}
int main()
{
	cin>>n>>m;
	k=vint(n);
	forn(i,n)
	cin>>k[i];
	for (int i = 0; i < m; ++i) {
		cin >> q[i].first >> q[i].second;
		--q[i].first;
		--q[i].second;
	}
	ll l=0;
	ll r=400000;
	while (r - l > 1) {
		int mid = (l + r) >> 1;
		if (can(mid)) r = mid;
		else l = mid;
	}

	for (int i = l; i <= r; ++i) {
		if (can(i)) {
			cout << i + 1 << endl;
			return 0;
		}
	}
}

//#include <bits/stdc++.h>
# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>
# include <unordered_set>
# include <unordered_map>
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>*/
#define ll long long
#define ld long double
#define vll vector <ll>
#define vvll vector <vll>
#define pll pair <ll, ll>
#define vpll vector <pll>

#define rep(i, a, b) for (ll i = a; i < b; i++)
#define per(i, a, b) for (ll i = a - 1; i >= b; --i)

#define endl "\n"
#define pb push_back
#define pf push_front

#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()

#define sorta(v) sort(all(v))
#define sortd(v) sort(rall(v))
#define vld vector<ld>

#define debug if (1)
#define log(val) debug {clog << "\n" << #val << ": " << val << "\n";}

#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

#define mod (ll)(1e9 + 7)
#define inf (mod * mod)

using namespace std;

const ll N = 2e5 + 5;

struct SegmentTree {
private:
    vll t;
    vll toAdd;
    ll n;

    ll merge(ll a, ll b) {
        return a + b;
    }

    void pull(ll it) {
        t[it] = merge(t[it * 2 + 1], t[it * 2 + 2]);
    }

    void build(ll l, ll r, ll it, vll &a) {
        if (l == r) {
            t[it] = a[l];
            return;
        }

        ll m = (l + r) / 2;

        build(l, m, it * 2 + 1, a);
        build(m + 1, r, it * 2 + 2, a);

        pull(it);
    }

    void push(ll v) {
        toAdd[v * 2 + 1] += toAdd[v];
        toAdd[v * 2 + 2] += toAdd[v];

        t[v * 2 + 1] += toAdd[v];
        t[v * 2 + 2] += toAdd[v];

        toAdd[v] = 0;
    }

    ll query(ll l, ll r, ll ql, ll qr, ll it) {
        if (ql > qr)
            return 0;
        if (l == ql && r == qr) {
            return t[it];
        }

        ll m = (l + r) / 2;

        push(it);

        return merge(
                   query(l, m, ql, min(qr, m), it * 2 + 1),
                   query(m + 1, r, max(m + 1, ql), qr, it * 2 + 2));
    }

    void change(ll l, ll r, ll ql, ll qr, ll val, ll it) {
        if (ql > qr)
            return;
        if (l == ql && r == qr) {
            t[it] += val;
            toAdd[it] += val;
            return;
        }

        ll m = (l + r) / 2;

        push(it);

        change(l, m, ql, min(qr, m), val, it * 2 + 1);
        change(m + 1, r, max(m + 1, ql), qr, val, it * 2 + 2);

        pull(it);
    }
public:
   SegmentTree(ll _n) {
        n = _n;
        t.resize(n * 4, 0);
        toAdd.resize(n * 4, 0);
    }

    void change(ll l, ll r, ll val) {
        if (l > r)
            swap(l, r);
        change(0, n - 1, l, r, val, 0);
    }

    ll query(ll l, ll r) {
        if (l > r)
            swap(l, r);
        return query(0, n - 1, l, r, 0);
    }

    void build(vll &a) {
        build(0, n - 1, 0, a);
    }
};

ll need[N];
//pll cost[N];
vll dayForType[N];

ll n, m;

ll f(ll days) {
    ll money = days;

    vll moneyOnDay(days + 1);
    iota(all(moneyOnDay), 0);

    auto st = SegmentTree(days + 1);
    st.build(moneyOnDay);

    rep(type, 0, n) {
        ll lastDayInd = upper_bound(all(dayForType[type]), days) - dayForType[type].begin() - 1;
        if (lastDayInd >= 0) {
            ll lastDay = dayForType[type][lastDayInd];

            ll moneyOnThatDay = st.query(lastDay, lastDay);
            ll willTakeOnDiscount = min(moneyOnThatDay, need[type]);

            //moneyOnDay[lastDay] -= willTakeOnDiscount;
            st.change(lastDay, days, -willTakeOnDiscount);

            money -= willTakeOnDiscount;
            money -= (need[type] - willTakeOnDiscount) * 2;
        } else {
            money -= need[type] * 2;
        }
    }

    return money >= 0;
}

ll bs(ll l, ll r) {
    if (l == r) {
        return l;
    }

    ll m = (l + r) / 2;

    if (f(m)) {
        return bs(l, m);
    } else {
        return bs(m + 1, r);
    }
}

void solve() {
    // don't forget about ios

    cin >> n >> m;
    rep(i, 0, n) {
        cin >> need[i];
    }

    rep(i, 0, m) {
        ll d, type;
        cin >> d >> type;
        type--;
        //cost[i] = {d, type};
        dayForType[type].pb(d);
    }

    rep(type, 0, n) {
        sorta(dayForType[type]);
    }

    //sort(cost, cost + n);

    ll days = bs(0, 1e6);

    cout << days;
}

int main() {
    ios
    // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())

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

    ll tests = 1;
    //cin >> tests;
    while (tests--) {
        solve();
        cout << "\n";
    }

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int >q[200010] ;
int a[200010];
int b[200010];
int main()
{
   int n,m;
   scanf("%d%d",&n,&m);
   int sum=0;
   for(int i=1;i<=n;i++) scanf("%d",&a[i]),sum+=a[i];
   for(int i=1;i<=m;i++)
   {
   	 int d,x;
   	 scanf("%d%d",&d,&x);
   	 q[d].push_back(x);
   }
   int l=0,r=2e5+10;int ans=0;
   while(l<=r)
   {
     int m=(l+r)>>1;for(int i=1;i<=n;i++) b[i]=0;
     int p=0,tot=0;
	 for(int i=1;i<=m;i++)
	 {
	   ++p;
	   for(int j=0;j<q[i].size();j++)
	   {
	   	 while(b[q[i][j]]<a[q[i][j]]&&p>0) p--,b[q[i][j]]++,tot++;
	   }
	 }
	 //cout<<m<<' '<<p<<' '<<tot<<endl;
	 if((sum-tot)*2<=p) ans=m,r=m-1;
	 else l=m+1;
   }
   printf("%d\n",ans);
}

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pai acos(-1)
const LL  mod = 1000000007;
const int MXN = 5e5+5;
int k[MXN];int last[MXN],need[MXN];
vector<int>v[MXN];
bool check(int x,int n){
    for(int i=1;i<=n;i++)need[i]=k[i];
    for(int i=1;i<=x;i++)v[i].clear();
    for(int i=1;i<=n;i++)v[last[i]].push_back(i);
    int money=0;
    for(int i=1;i<=x;i++){
        money++;
        for(auto it:v[i]){
            int lim=min(money,need[it]);
            money-=lim;need[it]-=lim;
        }
    }
    int sum=0;
    for(int i=1;i<=n;i++){
        sum=sum+need[i];
    }
    if(sum*2<=money)return 1;
    return 0;
}
int main(){
    int n,m;scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d",&k[i]);
    for(int i=1;i<=m;i++){
        int d,t;scanf("%d%d",&d,&t);
        last[t]=max(last[t],d);
    }
    int l=0,r=4e5,ans=-1;
    while(l<=r){
        int mid=(l+r)/2;
        if(check(mid,n)){
            ans=mid;
            r=mid-1;
        }
        else l=mid+1;
    }
    printf("%d\n",ans);
    return 0;
}

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

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

basic_string<int> e[200005];
int n, m;
int k[200005], sumk;
int lastday[200005];

bool probaj(int t) {
	int spent = 0, spendable = 0;
	for (int i=200000; i>=1; i--) {
		for (int x : e[i]) {
			spendable += k[x];
		}
		if (spendable > 0 && i <= t) {
			spendable--;
			spent++;
		}
	}

	cerr << "t = " << t << '\n';
	cerr << "spent = " << spent << '\n';

	return 2*sumk - spent <= t;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cerr.tie(nullptr);

	cin >> n >> m;
	for (int i=1; i<=n; i++) {
		cin >> k[i];
		sumk += k[i];
	}

	for (int i=0; i<m; i++) {
		int d, t;
		cin >> d >> t;
		lastday[t] = max(lastday[t], d);
	}

	for (int i=1; i<=n; i++) {
		e[lastday[i]] += i;
	}

	int l = 0, r = 600005, o = -1;
	while (l <= r) {
		int m = (l+r) >> 1;
		if (probaj(m)) {
			o = m;
			r = m - 1;
		} else {
			l = m + 1;
		}
	}
	cout << o << '\n';
}

#include <bits/stdc++.h>
#define ll  long long
#define ull unsigned long long
using namespace std;
#define  inf 1e9+18
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL)
#define mod  998244353
#define  f1(i,n) for(i=1;i<=n;i++)
#define f0(i,n)  for(i=0;i<n;i++)
#define w(x)   while(x--)
const int maxn=2002;
#define  pq priority_queue
#define  ff first
#define  ss second
#define pb  push_back
#define lb lower_bound
int a[maxn],n,m;
vector<int>v[maxn];
set<int>s;
bool solve(int days,int sum)
{
    int i,j,k,l=days;
    int b[n]={};
   for(i=0;i<n;i++)
   {
    b[i]=a[i];
   }

  int h=0;

  for(i=1;i<=days;i++)
  {
    h++;
   // cout<<h<<" ";
    if(v[i].size()>0)
    for(auto it:v[i])
    {
        if(h==0)
            break;
        int k=min(h,b[it-1]);
        b[it-1]-=k;
        h-=k;

    }
  }
  int le=0;
  for(i=0;i<n;i++)
  {
    le+=(b[i]);
  }
le=2*le;

return (le<=h);

}
int main()
{
   int t;
   ll i,j,l=0,k;
   cin>>n>>m;
   for(i=0;i<n;i++){
    cin>>a[i];
    l+=a[i];
}
   for(i=0;i<m;i++)
   {
    cin>>j>>k;
    v[j].pb(k);
    s.insert(j);

   }
  // sort(v.begin(),v.end());
  int low=1;

  int high=2000+5,ans=1;
  while(low<=high)
  {
    int mid=(low+high)/2;
    if(solve(mid,l))
    {
        ans=mid;
        high=mid-1;
    }
    else
    {
        low=mid+1;
    }
  }
  cout<<ans;
}

#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;

const int MAX_N = 1001;
const int MAX_M = 1001;
const int MAX_DAY = 2002;

bool is_sale[MAX_N];
ll K[MAX_N], D[MAX_M], T[MAX_M];
ll last_sale[MAX_N], tmp_k[MAX_N];
vector<ll> sale_target[MAX_DAY];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll N, M;
    cin >> N >> M;
    for (int i = 0; i < N; i++) {
        cin >> K[i];
    }
    for (int i = 0; i < M; i++) {
        cin >> D[i] >> T[i];
        T[i]--;
        is_sale[T[i]] = true;
    }
    ll not_sale = 0;
    for (int i = 0; i < N; i++) {
        if (!is_sale[i]) not_sale += K[i];
    }
    ll left = 0, right = 2002;
    while (right - left > 1) {
        ll mid = (right + left) / 2;
        for (int i = 0; i < N; i++) {
            last_sale[i] = 0;
            tmp_k[i] = K[i];
        }
        for (ll i = 0; i <= mid; i++) {
            sale_target[i].clear();
        }
        for (ll i = 0; i < M; i++) {
            if (D[i] > mid) continue;
            last_sale[T[i]] = max(last_sale[T[i]], D[i]);
        }
        for (int i = 0; i < N; i++) {
            if (last_sale[i] == 0) continue;
            sale_target[last_sale[i]].push_back(i);
        }
        ll money = 0, rest = not_sale;
        for (int i = 1; i <= mid; i++) {
            money++;
            if (sale_target[i].size() > 0) {
                for (int j = 0; j < sale_target[i].size(); j++) {
                    if (tmp_k[sale_target[i][j]] > money) {
                        tmp_k[sale_target[i][j]] -= money;
                        rest += tmp_k[sale_target[i][j]];
                        money = 0;
                    }
                    else {
                        money -= tmp_k[sale_target[i][j]];
                        tmp_k[sale_target[i][j]] = 0;
                    }
                }
            }
        }
        if (money >= 2 * rest) right = mid;
        else left = mid;
    }
    cout << right << endl;
    return 0;
}

#include <bits/stdc++.h>
//#include <boost/multiprecision/cpp_int.hpp>
//using namespace boost::multiprecision;
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;
typedef complex<ld> cd;

//ll ncr(ll n,ll r){ll ans=1;r=min(r,n-r);for (int i=1;i<=r;i++){ans*=(n-r+i);ans/=i;}return ans;}

#define pb push_back
#define eb emplace_back
#define mp(x,y) make_pair(x,y)
#define mod 1000000007

double PI=3.1415926535897932384626;

//template<typename T> T power(T x,T y,ll m=mod){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;}

#define bip(n) __builtin_popcount(n)//no of ones bit in binary!!
#define bictz(n) __builtin_ctz(n)//no of trailing zeroes in binary!!
#define biclz(n) __builtin_clz(n)//no of leading zeroes in binary!!
#define bffs(n) __builtin_ffs(n)//index of first one bit!!

typedef pair<int, int> ii;
typedef tuple<int, int, int> iii;

typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<ld> vd;
typedef vector<ll> vl;

//#define fi1 ifstream fin("input.txt")
//#define of1 ofstream fout("output.txt")
//typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ost;

#define fi first
#define se second

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	ll n,m;
	cin>>n>>m;
	vector<ll>arr(n+1);
	ll sum=0;
	for(ll i=1;i<=n;i++)
	{
		cin>>arr[i];
		sum+=arr[i];
	}
	map<ll,set<ll> >mm;
	for(ll u=0;u<m;u++)
	{
		ll d,t;
		cin>>d>>t;
		mm[d].insert(t);
	}
	ll money=0;
	ll day_count=0;
	while(sum>0)
	{
		day_count++;
		money++;
	//	cout<<day_count<<" "<<money<<endl;
		if(!mm.empty() && (mm.begin()->fi==day_count) )
		{
			for(auto &x:(mm.begin()->se))
			{
				ll noo=min(money,arr[x]);
				money-=noo;
				arr[x]-=noo;
				sum-=noo;
				if(money==0)
					break;
			}
			mm.erase(mm.begin());
			if(money>0)
			{
				ll value=money/2;
				for(ll i=1;i<=n;i++)
				{
					if(arr[i]>0)
					{
						ll noo=min(arr[i],value);
						arr[i]-=noo;
						value-=noo;
						money-=(noo*2);
						sum-=(noo);
					}
					if(money==0)
						break;
				}
			}
		}
		else
		{
			ll value=money/2;
			for(ll i=1;i<=n;i++)
			{
				if(arr[i]>0)
				{
					ll noo=min(arr[i],value);
					arr[i]-=noo;
					value-=noo;
					money-=(noo*2);
					sum-=(noo);
				}
				if(money==0)
					break;
			}
		}
	}
	cout<<day_count;
    return 0;
}

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <bitset>

using namespace std;

#define INF 10000000

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

	long long n, m, i, j, k, a, b, c, d, id, s, total, last, x;
	cin >> n >> m;
	vector<long long> needed(n + 1, 0), v;
	vector<vector<long long>> sales(n + 1);
	vector<pair<long long, long long>> plist(n + 1);
	for (i = 1; i <= n; i++) cin >> needed[i];
	for (i = 1; i <= m; i++) {
		cin >> d >> id;
		sales[id].push_back(d);
	}
	for (i = 1; i <= n; i++) {
		sales[i].push_back(INF);
		sort(sales[i].begin(), sales[i].end());
	}

	a = 1; b = 500000;

	while (a < b) {
		c = (a + b) / 2;

		plist[0] = { -1, -1 };
		for (i = 1; i <= n; i++) {
			if (sales[i].size() == 1) x = INF;
			else {
				vector<long long>::iterator it = upper_bound(sales[i].begin(), sales[i].end(), c);
				it--;
				x = *it;
			}
			plist[i] = { x , i };
		}
		sort(plist.begin(), plist.end());

		s = 0;
		v = needed;		// volume
		last = 0;
		for (i = 1; i <= n; i++) {
			if (plist[i].first <= c) {
				s += plist[i].first - last;		// money earned
				d = min(s, v[plist[i].second]);		// quantity to purchase
				v[plist[i].second] -= d;
				s -= d;
				last = plist[i].first;
			}
		}
		s += (c - last);
		for (i = 1; i <= n; i++) s -= 2 * v[i];
		if (s >= 0) b = c;
		else a = c + 1;
	}

	//if (a == 1) {
	//	c = 0; d = 0;
	//	for (i = 1; i <= n; i++) {
	//		//if (needed[i] > 0) cout << i << "-" << needed[i] << " ";
	//		if (needed[i] > 0) c+= needed[i];
	//		if ((needed[i] > 0) && (sales[i].size() != 1)) d++;
	//	}
	//	cout << c << " " << d << "\n";
	//	for (i = 1; i <= n; i++) {
	//		id = plist[i].second;
	//		//if ((needed[id] > 0)) cout << id << "-" << needed[id] << "-" << plist[i].first << " ";
	//		if ((needed[id] > 0)) cout << id << "-" << needed[id] << "-" << *sales[id].begin() << " ";
	//	}
	//	cout << "\n";
	//}

	cout << a << "\n";

	return 0;
}

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 102400;

int n,m,summ,k[maxn],cnt[maxn];
vector<int> d[maxn];

bool judge(int mid)
{
  int c = 0,tmp = 0;
  memset(cnt,0,sizeof(cnt));
  for(int i=1;i<=mid;i++)
  {
    c++;
    for(auto j:d[i])
    {
      if(c == 0) break;
      if(cnt[j] < k[j])
      {
        int cc = min(c,k[j]-cnt[j]);
        tmp += cc;
        cnt[j] += cc;
        c -= cc;
      }
    }
  }
  tmp += (mid-tmp)/2;
  if(tmp >= summ) return true;
  else return false;
}

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);cout.tie(0);
  int a,b;
  cin >> n >> m;
  for(int i=1;i<=n;i++) {cin >> k[i];summ += k[i];}
  for(int i=0;i<m;i++)
  {
    cin >> a >> b;
    d[a].push_back(b);
  }
  int l=1,r = 2*summ+1,mid,ans = r;
  while(l <= r)
  {
    mid = (l + r) >> 1;
    if(judge(mid)) {ans = mid;r = mid-1;}
    else l = mid + 1;
  }
  cout << ans << endl;
}

#include<bits/stdc++.h>

using namespace std;

#define ff first
#define ss second

int main()
{
    int n,m;
    cin >> n >> m;
    int a[n];
    long long int sum=0;
    for(int i=0;i<n;i++)
    {
        cin >> a[i];
        sum+=a[i];
    }
    pair<int,int> b[m];
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin >> x >> y;
        b[i]=make_pair(x,y);
    }
    int late[n]={0};
    sort(b,b+m);
    for(int i=0;i<m;i++)
    {
        late[b[i].ss]=b[i].ff;
    }
    /*for(int i=0;i<m;i++)
        cout << b[i].ff << " ";
    cout << endl;*/
    long long int low=0,high=2*sum,ans=0;
    while(low<=high)
    {
        long long int mid=(high+low)/2,t=sum,t2=0;
        int j=0,pre=0;
        int d[n];
        for(int i=0;i<n;i++)
            d[i]=a[i];
        for(int i=0;i<m&&b[i].ff<=mid;i++)
        {
            if(late[b[i].ss]!=b[i].ff)
                continue;
            j+=b[i].ff-pre;
            t-=min(d[b[i].ss-1],j);
            int t1=d[b[i].ss-1];
            d[b[i].ss-1]-=min(d[b[i].ss-1],j);
            j=max(0,j-t1);
            t2=mid-b[i].ff;
            pre=b[i].ff;
            //cout << b[i].ff << " " << t << endl;
        }
        j+=t2;
        if(2*t<=j)
        {
            ans=mid;
            high=mid-1;
        }
        else
            low=mid+1;
    }
    if(ans==0)
        cout << sum;
    cout << ans;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
ll blur;
ll k[1005], kk[1005];
vector<int> sale_d[2005];
set<int> sale_t[2005];
bool check(int day){
    if (day < 0) return false;
    blur = 0;
    for (int i=1;i<=n;i++){
        kk[i] = k[i];
    }
    vector<int> sale_back;
    for (int d=1;d<=day;d++){
        blur++;
        // check sale
        sale_back.clear();
        for (int i=0;i<sale_d[d].size();i++){
            int type = sale_d[d][i];
            if ( *(sale_t[type].upper_bound(d)) <= day ) {
                sale_back.push_back(type);
                continue;
            }
            int x = min(blur, kk[type]);
            blur -= x;
            kk[type] -= x;
        }
        for (int i=0;i<sale_back.size();i++){
            int type = sale_back[i];
            int x = min(blur, kk[type]);
            blur -= x;
            kk[type] -= x;
        }
    }
    ll cnt = 0;
    for (int i=1;i<=n;i++){
        cnt += kk[i];
    }
    if (blur>=cnt*2) return true;
    else return false;
}
int bs(int day){
    if (check(day)){
        if (check(day-1)){
            return 1; // too large
        }else{
            return 0; // found
        }
    }else{
        return -1; // too small
    }

}

int main(void){
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        cin >> k[i];
    }
    for (int i=0;i<m;i++){
        int d,t;
        cin >> d >> t;
        sale_d[d].push_back(t);
        sale_t[t].insert(t);
    }
    int u = 0, v = 2005, cur = -1;
    while(u<v){
        cur = (u+v)/2;
        int res = bs(cur);
        if (res == 0){
            break;
        }else if (res == -1){
            u = cur+1;
        }else{
            v = cur;
        }
    }
    assert(cur!=-1);
    cout << cur << endl;
}

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+1000;
int a[maxn],c[maxn];
struct node
{
	int d,t;
	friend bool operator<(const node &a,const node &b)
	{
		return a.d<b.d;
	}
}b[maxn];
int n,m;
bool check(int x)
{
	int sum=0;
	for(int i=1;i<=n;i++)
		sum+=a[i],c[i]=a[i];
	int num=0;
	for(int i=1;i<=m;i++)
	{
		if(b[i].d<=x&&c[b[i].t]>0)
		{
			int t=b[i].d;
			while(1)
			{
				if(t-num>0&&c[b[i].t]>0)
				{
					sum--;
					c[b[i].t]--;
					x--;
					num++;
				}
				else break;
			}
		}
	}
	if(sum*2<=x) return true;
	else return false;
}
int main()
{
	//int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	for(int i=1;i<=m;i++)
		cin>>b[i].d>>b[i].t;
	sort(b+1,b+1+m);
	int l=0,r=1e9;
	int ans;
	while(l<=r)
	{
		int mid=(l+r)/2;
		if(check(mid))
		{
			ans=mid;
			r=mid-1;
		}
		else l=mid+1;
	}
	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define int int64_t
const int M = 2e5 + 5;
int n, m, a[M], b[M], trans;
map <int, vector <int> > mp;

int OK(int day)
{
	int burles = 0;
	for(int i = 1; i <= n; i++)
		b[i] = a[i];
	for(int d = 1; d <= day; d++)
	{
		burles++;
		for(auto i : mp[d])
		{
			if(!burles)
				break;
			int tmp = min(burles, b[i]);
			burles -= tmp;
			b[i] -= tmp;
		}
	}
	for(int i = 1; i <= n; i++)
	{
		if(burles <= 1)
			break;
		int tmp = min(burles / 2, b[i]);
		burles -= (tmp * 2);
		b[i] -= tmp;
	}
	for(int i = 1; i <= n; i++)
		if(b[i])
			return 0;
	return 1;
}

int32_t main()
{
	#ifndef ONLINE_JUDGE
	    freopen("in.txt", "r", stdin);
	    freopen("out.txt", "w", stdout);
	#endif
	ios_base::sync_with_stdio(0);	cin.tie(0);	cout.tie(0);
	cin >> n >> m;
	for(int i = 1; i <= n; i++)	cin >> a[i];
	for(int i = 1; i <= m; i++)
	{
		int d, t;	cin >> d >> t;
		mp[d].push_back(t);
	}
	int start = 1, end = 1e6, ans = -1;
	while(start <= end)
	{
		int mid = (start + end) >> 1;
		if(OK(mid))
		{
			ans = mid;
			end = mid - 1;
		}
		else
			start = mid + 1;
	}
	cout << ans;
	return 0;
}

#include <bits/stdc++.h>

#define INF 2.1e9
#define EPS 1e-8
#define pb push_back
#define pause system("pause")
#define exit exit(0)
#define endl '\n'

using namespace std;
using ull = unsigned long long;
using ll = long long;

typedef pair<int, int> pii;
const int N = 200005;

int n, m, sum;
int k[N], lst[N], d[N], t[N];
vector<int> p[2 * N];

bool check(int x) {
	fill(lst, lst + N, 0);
	for (int i = 0; i < m; ++i) {
		lst[t[i]] = max(lst[t[i]], d[i]);
	}

	for (int i = 1; i <= n; ++i) p[i].clear();
	for (int i = 1; i <= n; ++i) {
		if (lst[i] != 0) {
			p[lst[i]].pb(i);
		}
	}

	int sm = sum, curr = 0;
	for (int i = 1; i <= x; ++i) {
		++curr;
		for (auto x : p[i]) {
			int y = min(k[x], curr);
			curr -= y, sm -= y;
		}
	}

	return 2 * sm <= curr;
}

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

	cin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		cin >> k[i];
		sum += k[i];
	}

	for (int i = 0; i < m; ++i) {
		cin >> d[i] >> t[i];
	}

	int l = 0, r = 2 * N, m;
	while (r - l > 1) {
		m = (l + r) >> 1;
		if (check(m)) {
			r = m;
		} else {
			l = m;
		}
	}

	cout << r << endl;
	//pause;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
namespace fastIO{
	#define BUF_SIZE 100000
	#define OUT_SIZE 100000
	//fread->read
	bool IOerror=0;
//  inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;}
	inline char nc(){
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend){
			p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1){IOerror=1;return -1;}
		}
		return *p1++;
	}
	inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';}
	template<class T> inline bool read(T &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	inline bool read(double &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(ch=='.'){
			double tmp=1; ch=nc();
			for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0');
		}
		if(sign)x=-x;
		return true;
	}
	inline bool read(char *s){
		char ch=nc();
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch;
		*s=0;
		return true;
	}
	inline bool read(char &c){
		for(c=nc();blank(c);c=nc());
		if(IOerror){c=-1;return false;}
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);}
	#undef OUT_SIZE
	#undef BUF_SIZE
};
using namespace fastIO;
/************* debug begin *************/
string to_string(string s){return '"'+s+'"';}
string to_string(const char* s){return to_string((string)s);}
string to_string(const bool& b){return(b?"true":"false");}
template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();}
template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";}
template<class A>string to_string(const vector<A> v){
	int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}";
	return res;
}
void debug_out(){puts("");}
template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);}
#ifdef tokitsukaze
#define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__);
#else
#define debug(...) 233;
#endif
/*************  debug end  *************/
#define mem(a,b) memset((a),(b),sizeof(a))
#define MP make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
#define sqr(x) (x)*(x)
using namespace __gnu_cxx;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef pair<int,ll> PIL;
typedef pair<ll,int> PLI;
typedef vector<int> VI;
typedef vector<ll> VL;
/************* define end  *************/
void read(int *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void read(ll *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void read(double *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);}
void println(VI x){for(int i=0;i<sz(x);i++) printf("%d%c",x[i]," \n"[i==sz(x)-1]);}
void println(VL x){for(int i=0;i<sz(x);i++) printf("%lld%c",x[i]," \n"[i==sz(x)-1]);}
void println(int *x,int l,int r){for(int i=l;i<=r;i++) printf("%d%c",x[i]," \n"[i==r]);}
void println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf("%lld%c",x[i]," \n"[i==r]);}
/*************** IO end  ***************/
void go();
int main(){
	#ifdef tokitsukaze
		freopen("TEST.txt","r",stdin);
	#endif
	go();return 0;
}
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3fLL;
const double PI=acos(-1.0);
const double eps=1e-6;
const int MAX=4e5+10;
const ll mod=998244353;
/*********************************  head  *********************************/
struct Segment_Tree
{
	#define type int
	#define ls (id<<1)
	#define rs (id<<1|1)
	int n,ql,qr;
	type a[MAX],v[MAX<<2],tag[MAX<<2],qv;
	void pushup(int id)
	{
		v[id]=min(v[ls],v[rs]);
	}
	void pushdown(int id)
	{
		if(!tag[id]) return;

	}
	void build(int l,int r,int id)
	{
		tag[id]=0;
		if(l==r)
		{
			v[id]=a[l];
			return;
		}
		int mid=(l+r)>>1;
		build(l,mid,ls);
		build(mid+1,r,rs);
		pushup(id);
	}
	void update(int l,int r,int id)
	{
		if(l>=ql&&r<=qr)
		{
			v[id]=qv;
			return;
		}
		pushdown(id);
		int mid=(l+r)>>1;
		if(ql<=mid) update(l,mid,ls);
		if(qr>mid) update(mid+1,r,rs);
		pushup(id);
	}
	type res;
	void query(int l,int r,int id)
	{
		if(l>=ql&&r<=qr)
		{
			res=min(res,v[id]);
			return;
		}
		pushdown(id);
		int mid=(l+r)>>1;
		if(ql<=mid) query(l,mid,ls);
		if(qr>mid) query(mid+1,r,rs);
	}
	void build(int _n){n=_n;build(1,n,1);}
	void upd(int l,int r,type v)
	{
		ql=l;
		qr=r;
		qv=v;
		update(1,n,1);
	}
	type ask(int l,int r)
	{
		ql=l;
		qr=r;
		res=INF;
		query(1,n,1);
		return res;
	}
	#undef type
	#undef ls
	#undef rs
}tr;
VI mp[MAX];
int v[MAX],mx[MAX],pos[MAX];
int ck(int n,int x)
{
	int i,res,now;
	set<PII > s;
	mem(mx,0);
	for(i=1;i<=n;i++)
	{
		if(v[i])
		{
			s.insert(MP(v[i],i));
			for(auto it:mp[i])
			{
				if(it<=x)
				{
					mx[i]=it;
					break;
				}
			}
		}
	}
	res=0;
	for(i=1;i<=x;i++) pos[i]=tr.a[i]=i;
	tr.build(x);
	while(sz(s))
	{
		PII tmp=*s.rbegin();
		s.erase(tmp);
		now=tr.ask(pos[mx[tmp.se]],x);
		if(mx[tmp.se]&&now)
		{
			res++;
			pos[mx[tmp.se]]=now-1;
			tr.upd(mx[tmp.se],mx[tmp.se],now-1);
		}
		else res+=2;
		tmp.fi--;
		if(tmp.fi>0) s.insert(tmp);
	}
	return res<=x;
}
void go()
{
	int n,m,i,a,b,l,r,mid;
	while(read(n,m))
	{
		read(v,1,n);
		for(i=1;i<=n;i++) mp[i].clear();
		while(m--)
		{
			read(a,b);
			mp[b].pb(a);
		}
		for(i=1;i<=n;i++)
		{
			sort(all(mp[i]));
			reverse(all(mp[i]));
		}
		l=0;
		r=4e5;
		while(l<r)
		{
			mid=(l+r)>>1;
			if(ck(n,mid)) r=mid;
			else l=mid+1;
		}
		printf("%d\n",l);
	}
}

#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
using namespace std;
#define cerr if(0)cerr
#define watch(x) cerr << (#x) << " is " << (x) << endl
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define max3(x,y,z) max(x,max(y,z))
#define min3(x,y,z) min(x,min(y,z))
#define MOD 1000000007  //1e9 + 7
#define INF 2000000000 //2e9
#define DESPACITO 1000000000000000000 //1e18
#define PI acos(-1);
#define E 998244353
#define ins insert
#define pb push_back
#define mp make_pair
#define sz(x) (int)(x).size()
#define X first
#define Y second
#define lb lower_bound
#define ub upper_bound
#define ll long long
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 1e5 + 5;
int n, m, d, t;
map <int,vector <int>> day;
vector<int> k;

bool check (int x) {
    ll cash = 0, last = 0;
    vector<int> tempk(k);
    for(auto &[o, p] : day) {
        if (o > x) break;
        cash += o-last;
        last = o;
        //cout << "o: " << o << endl;
        for (auto& s: p) {
            //cout << s << " ";
            int take = min(tempk[s-1], cash);
            tempk[s-1] -= take;
            cash -= take;
        }
        //cout << endl;
    }
    cash += x-last;
    ll left = 0;
    for (int i = 0; i < n; i++)
        left += tempk[i];
    left *= 2;
    return (left <= cash);
}

int binarySearch(int low, int high) {
    while(low < high) {
        int mid = (low + high) / 2;
        //cout << "mid " << mid << endl;
        if(!check(mid))
            low = mid + 1;
        else
            high = mid;
    }
    return low;
}

int32_t main() {
    IOS;
    int i, a;
    cin >> n >> m;
    for(i = 0; i < n; i++)
        cin >> a, k.pb(a);
    for(i = 1; i <= m; i++)
        cin >> d >> t, day[d].pb(t);
    /*for (auto& [q, v]: day) {
        cout << "day " << q << ": ";
        if (!sz(v)) {
            cout << 0;
            continue;
        }
        for (auto& x: v)
            cout << x << " ";
        cout << endl;
    }*/
    cout << binarySearch(1, 4e5+1);
    return 0;
}

#include<bits/stdc++.h>
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long INT;
typedef pair<int,int> pii;
#define NN 200200
int a[NN],fl[NN],b[NN],c[NN],mx[NN];
pii p[NN];
vector <int> vec[NN],adj[NN];
int main(){
#ifndef ONLINE_JUDGE
	freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
#endif
	int n,m,s=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++) scanf("%d",a+i),s+=a[i];
	for(int i=1;i<=m;i++) scanf("%d%d",&p[i].y,&p[i].x);
	sort(p+1,p+m+1);
	for(int i=1;i<=m;i++) vec[p[i].x].pb(p[i].y);
	int st=0,ed=2*s;
	while(st+1<ed){
		int mid=st+ed>>1;
		for(int i=1;i<=n;i++){
			int r=upper_bound(vec[i].begin(),vec[i].end(),mid)-vec[i].begin();
			if(r>0) adj[vec[i][r-1]].pb(i);
			b[i]=a[i];
		}
		int mo=0;
		for(int i=1;i<=mid;i++){
			mo++;
			for(int v:adj[i]){
				if(mo>a[v]) mo-=b[v],b[v]=0;
				else {b[v]-=mo;mo=0;break;}
			}
		}
		int tt=0;
		for(int i=1;i<=n;i++) tt+=b[i];
		mo-=tt*2;
		if(mo>=0) ed=mid;
		else st=mid;
		for(int i=1;i<=200000;i++) adj[i].clear();
	}
	cout<<ed<<endl;
	return 0;
}

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <bitset>

using namespace std;

#define INF 10000000

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

	long long n, m, i, j, k, a, b, c, d, id, s, total, last, x, ss;
	cin >> n >> m;
	vector<long long> needed(n + 1, 0), v;
	vector<vector<long long>> sales(n + 1);
	vector<pair<long long, long long>> plist(n + 1);
	total = 0;
	for (i = 1; i <= n; i++) {
		cin >> needed[i];
		total += needed[i];
	}
	for (i = 1; i <= m; i++) {
		cin >> d >> id;
		sales[id].push_back(d);
	}
	for (i = 1; i <= n; i++) {
		sales[i].push_back(INF);
		sort(sales[i].begin(), sales[i].end());
	}

	a = 0; b = 500000;

	bool debug = false;
	if ((n == 200000) && (total == 1) && (needed[176187] > 0)) debug = true;

	while (a < b) {
		c = (a + b) / 2;

		plist[0] = { -1, -1 };
		for (i = 1; i <= n; i++) {
			if (sales[i].size() == 1) x = INF;
			else {
				vector<long long>::iterator it = upper_bound(sales[i].begin(), sales[i].end(), c);
				it--;
				x = *it;
			}
			plist[i] = { x , i };
		}
		sort(plist.begin(), plist.end());

		s = 0;
		v = needed;		// volume
		last = 0;
		for (i = 1; i <= n; i++) {
			if (plist[i].first <= c) {
				s += plist[i].first - last;		// money earned
				d = min(s, v[plist[i].second]);		// quantity to purchase
				v[plist[i].second] -= d;
				s -= d;
				last = plist[i].first;
			}
			else break;
		}
		ss = s;
		s += (c - last);
		for (i = 1; i <= n; i++) {
			if (v[i] > 0) s -= 2LL * v[i];
			if (s < 0) break;
		}

		if (debug) cout << c << " " << s << " " << ss << " " << last << "\n";

		if (s >= 0) b = c;
		else a = c + 1;

	}

	cout << a << "\n";

	if (a == 199999) {
		c = 0; d = 0;
		for (i = 1; i <= n; i++) {
			//if (needed[i] > 0) cout << i << "-" << needed[i] << " ";
			if (needed[i] > 0) c+= needed[i];
			if ((needed[i] > 0) && (sales[i].size() != 1)) d++;
		}
		cout << c << " " << d << "\n";
		for (i = 1; i <= n; i++) {
			id = plist[i].second;
			//if ((needed[id] > 0)) cout << id << "-" << needed[id] << "-" << plist[i].first << " ";
			//if ((needed[id] > 0))
				cout << i << ">" << id << "-" << needed[id] << "-" << *sales[id].begin() << " ";
		}
		cout << "\n";
	}

	return 0;
}

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

const int MAX_N = 1001;
const int MAX_M = 1001;
const int MAX_DAY = 2002;

bool is_sale[MAX_N], is_checked[MAX_N];
int K[MAX_N], D[MAX_M], T[MAX_M];
int last_sale[MAX_N];
vector<int> sale_target[MAX_DAY];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N, M, sum = 0;
    cin >> N >> M;
    for (int i = 0; i < N; i++) {
        cin >> K[i];
        sum += K[i] * 2;
    }
    for (int i = 0; i < M; i++) {
        cin >> D[i] >> T[i];
        T[i]--;
        is_sale[T[i]] = true;
    }
    int not_sale = 0;
    for (int i = 0; i < N; i++) {
        if (!is_sale[i]) not_sale += K[i];
    }
    int left = 0, right = sum;
    while (right - left > 1) {
        int mid = (right + left) / 2;
        for (int i = 0; i < N; i++) {
            is_checked[i] = false;
            last_sale[i] = 0;
        }
        for (int i = 0; i <= mid; i++) {
            sale_target[i].clear();
        }
        for (int i = 0; i < M; i++) {
            if (D[i] > mid) continue;
            last_sale[T[i]] = max(last_sale[T[i]], D[i]);
        }
        for (int i = 0; i < N; i++) {
            sale_target[last_sale[i]].push_back(i);
        }
        int money = 0, rest = not_sale;
        for (int i = 1; i <= mid; i++) {
            money++;
            if (sale_target[i].size() > 0) {
                for (int j = 0; j < sale_target[i].size(); j++) {
                    if (is_checked[sale_target[i][j]]) continue;
                    if (K[sale_target[i][j]] > money) {
                        rest += K[sale_target[i][j]] - money;
                        money = 0;
                    }
                    else {
                        money -= K[sale_target[i][j]];
                    }
                    is_checked[sale_target[i][j]] = true;
                }
            }
        }
        if (money >= 2 * rest) right = mid;
        else left = mid;
    }
    cout << right << endl;
    return 0;
}

/* Things to do:
1.Beware!!! don't ever talk of your crush in front of your gf #Most important
2.Question do baar padhna
3.Constraints check krna
4.Sample test pr idea run krna

// Now start coding
*/

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

#define ll long long
#define pb push_back
#define Mod 998244353
#define pa pair<ll,ll>

int main()
{
    ll n,m,i,a,b,p=0,ans=0,brl=0,sum=0;
    cin>>n>>m;
    ll A[n];
    for(i=0;i<n;i++)
        cin>>A[i];
    set <pa> st;
    for(i=0;i<m;i++)
    {
        cin>>a>>b;
        if(A[b-1]!=0)
            st.insert({a,b});
    }
    ll cnt_sale[200010]={0};
    vector <pa> se[200010];
    set <pa> se1;
    for(auto it=st.begin();it!=st.end();++it)
    {
        a=it->first;
        b=it->second;
        cnt_sale[b]++;
        p=max(a,p);
    }
    for(auto it=st.begin();it!=st.end();++it)
    {
        a=it->first;
        b=it->second;
        se[a].pb({cnt_sale[b],b});
    }
    for(i=0;i<n;i++)
        sum+=A[i];
    if(n==1000)
        cout<<p<<endl;
    for(i=1;i<=p;i++)
    {
        if(se[i].size()==0)
        {
            brl++;
        }
        else
        {
            brl++;
            for(auto it=se[i].begin();it!=se[i].end();++it)
            {
                a=it->first;
                b=it->second;
                if(cnt_sale[b]>0)
                    se1.insert({cnt_sale[b],b});
            }
            for(auto it=se1.begin();it!=se1.end();++it)
            {
                a=it->first;
                b=it->second;
                cnt_sale[b]--;
                if(A[b-1]>=brl)
                {
                    A[b-1]=A[b-1]-brl;
                    sum=sum-brl;
                    brl=0;
                }
                else
                {
                    sum=sum-A[b-1];
                    brl=brl-A[b-1];
                    A[b-1]=0;
                }
            }
            se1.clear();
        }
        if(brl>=2*sum)
        {
            brl=0;
            sum=0;
            p=i;
            goto end;
        }
    }
    sum=0;
    for(i=0;i<n;i++)
        sum+=A[i];
    if(n==1000)
    {
        cout<<sum<<" "<<brl<<endl;
    }
    end:;
    ans=2*sum-brl+p;
    cout<<ans<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n,m,res,a[500500],b[500500],all,x,y;
vector<ll>  Offer[500500];///offers in day i
bool ok(ll days)
{
    for(ll i=1 ; i<=n ; i++)
        b[i]=a[i];
    ll money=0,buy=0;
    for(ll d=1 ; d<=days ; d++)
    {
        money++;
        for(ll i=0 ; i<Offer[d].size() ; i++)
        {
            if(!money)
                break;
            ll can=min(money,b[Offer[d][i]]);
            money-=can;
            b[Offer[d][i]]-=can;
            buy+=can;
        }
    }
    return ((all-buy)*2<=money);
}
int main()
{
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for(ll i=1 ;  i<=n ; i++)
        cin>>a[i] , all+=a[i];
    while(m--)
    {
        cin>>x>>y;
        Offer[x].push_back(y);
    }
    ll  St=1,End=all*2;
    while(St<=End)
    {
        ll mid=(St+End)/2;
        if(ok(mid))
        {
            res=mid;
            End=mid-1;
        }
        else
            St=mid+1;
    }
    cout<<res<<endl;
    return 0;
}

// end of patience
#include<bits/stdc++.h>
using namespace std ;
#define int long long int
#define F first
#define S second
#define pb push_back
int a[4000005] , b[4000005] ;
vector<int> adj[4000005] ;
int check( int k , int tot )
{
    int cnt = 0 , ans = 0 ;
    for( int i = 1 ; i <= k ; i++ )
    {
        cnt++ ;
        for( int j = 0 ; j < (int)adj[i].size() ; j++ )
        {
            int x = adj[i][j] ;
            if( cnt > a[x] )
                tot -= a[x] , cnt -= a[x] ;
            else
                tot -= cnt , cnt = 0 ;
        }
    }
    if( cnt >= 2*tot )
        return 1 ;
    return 0 ;
}
signed main()
{
    ios_base::sync_with_stdio(false) ;
    cin.tie(0) ; cout.tie(0) ;
    int n , m ;
    cin >> n >> m ;
    int tot = 0 ;
    for( int i = 1 ; i <= n ; i++ )
        cin >> a[i] , tot += a[i] ;
    for( int i = 0 ; i < m ; i++ )
    {
        int x , y ;
        cin >> x >> y ;
        b[y] = max( b[y] , x ) ; // last day of sale of y
    }
    for( int i = 1 ; i <= n ; i++ )
    adj[b[i]].push_back(i) ;
    int ans ;
    for( int i = 1 ; i <= 2*tot + 10 ; i++ )
    {
        if( check(i,tot) )
        return cout << i , 0 ;
    }
    cout << ans ;
    cerr << "Time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec \n";
}

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
int v[200200];
ii w[200200];
int main() {
	int n,m;
	int sk = 0;
	scanf("%d %d ",&n,&m);
	for(int i=0;i<n;i++) {
		int t;
		scanf("%d ",&t);
		v[i] = t;
		sk += t;
	}
	for(int i=0;i<m;i++) {
		int a,b;
		scanf("%d %d ",&a,&b);
		b--;
		w[i] = {a,b};
	}
	sort(w,w+m);
	int ct = 0;
	int mn = 0;
	int id = 0;
	while(1) {
		ct++;mn++;
		while(id < m && w[id].first <= ct) {
			int tr = min(v[w[id].second],mn);
			mn -= tr;
			v[id] -= tr;
			sk -= tr;
			id++;
		}
		if(mn >= sk*2) {break;}
	}
	printf("%d\n",ct);
}

/* ****TCIITB**** */

#include<bits/stdc++.h>
#define io          ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll          long long
#define pb          push_back
#define	endl		'\n'
#define pii         pair<ll int,ll int>
#define vi          vector<ll int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define hell        1000000007
#define rep(i,a,b)	for(int i=a;i<b;i++)
#define lbnd        lower_bound
#define ubnd        upper_bound
#define bs          binary_search
#define mp          make_pair
#define time        cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
using namespace std;

#define N  600006
set<pair<ll,ll>> adj[N];
std::vector<ll> cost(N);
ll sl[N];
std::vector<pii> ed;
int main()
{

	io
	ll n,m;
	cin>>n>>m;

	ll cnt=0;
	rep(i,1,n+1)
	{
		cin>>cost[i];
		cnt+=cost[i];
	}

	rep(i,0,m)
	{
		ll x,y;
		cin>>x>>y;
		ed.pb({x,y});
		sl[y]=max(sl[y],x);
	}
	rep(i,0,m)
	{
		ll s1=ed[i].F;
		ll s2=ed[i].S;
		adj[s1].insert({sl[s2],s2});
	}
	ll cd=1,cb=1,cr=0;
	cr+=(2*cnt);
	while(1)
	{
		if(adj[cd].size()!=0)
		{
			if(cb>=1)
			{
				for(auto i:adj[cd])
				{
					if(cost[i.S]==0)
						continue;
					if(cb==0 || cr==0)
						break;
					ll z=min(cost[i.S],cb);
					cost[i.S]-=z;
					cb-=z;
					cr-=(2*z);
					if(cb==0 || cr==0)
						break;
				}
			}
		}
		else
		{
			if(cb>=cr)
			{
				break;
			}
		}
		if(cr==0 || cb>=cr)
			break;
		cd++;
		cb++;
	}
	cout<<cd;
}

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int n,m,a[200100],t,d,b[200100];
set < int > st[200100];
vector <pair < int, int > > v;
set < pair < int , int > > Days;
set < pair < int , int > >::iterator it;

int main()
{
    cin>>n>>m;
    int sum = 0;
    for(int i=1; i<=n; i++)  cin>>a[i],sum+=a[i],b[i]=a[i];
    int Start = 1, End = 5e5, Answer;
    for(int i=1; i<=m; i++)
    {
        cin>>d>>t;
        st[t].insert(d);
    }
    for(int i=1; i<=2e5; i++)
    {
        if(st[i].size())  v.push_back({st[i].size(),i});
    }
    sort(v.begin(),v.end());
    for(int i=0;i<v.size();i++){
        for(auto x : st[v[i].second])  Days.insert({x,v[i].second});
    }
    while(Start <= End)
    {
        int mid = (Start + End)/2;
        int cnt = 0,Left = 0;
        for(it = Days.begin() ; it!=Days.end() ;it++){
            if(it->first > mid)  break;
            cnt+=min(a[it->second] , it->first - Left);
            Left+=min(a[it->second] , it->first - Left);
            a[it->second]-=min(a[it->second] , it->first - Left);
        }
        for(int i=1;i<=n;i++)  a[i]=b[i];
        if(cnt + (sum - cnt)*2 > mid)  Start = mid+1;
        else  Answer = mid, End = mid-1;
    }
    cout<<Answer;
    return 0;
}

#pragma GCC optimize("O3")
#include<bits/stdc++.h>
#define ll long long

const int MX=2e5+10;

using namespace std;

int main()
{
	cin.tie(0),ios::sync_with_stdio(0);
	int n,m;
	cin>>n>>m;
	vector<int> arr(n);
	int sum=0;
	for(int i=0;i<n;i++)
		cin>>arr[i],sum+=arr[i];
	vector<pair<int,int>> s(m);
	vector<int> v(n);
	for(int i=0;i<m;i++)
		cin>>s[i].first>>s[i].second,s[i].second--;
	sort(s.begin(),s.end());
	s.resize(unique(s.begin(),s.end())-s.begin());
	int l=1,r=MX+5,k;
	while(l<r)
	{
		k=(l+r)>>1;
		for(int i=0;i<m&&s[i].first<=k;i++)
			v[s[i].second]=s[i].first;
		int cnt=sum,p=0;
		for(int i=1,j=0;i<=k;i++)
		{
			p++;
			while(j<m&&s[j].first==i)
			{
				if(v[s[j].second]==i)
				{
					int tmp=min(p,arr[s[j].second]);
					p-=tmp;
					cnt-=tmp;
				}
				j++;
			}
		}
		if(cnt*2<=p)
			r=k;
		else
			l=k+1;
	}
	if(l!=MX+5)
	{
		cout<<l<<'\n';
		return 0;
	}
	for(int i=0;i<m;i++)
		v[s[i].second]=s[i].first;
	int cnt=sum,p=0;
	for(int i=1,j=0;i<=MX;i++)
	{
		p++;
		while(j<m&&s[j].first==i)
		{
			if(v[s[j].second]==i)
			{
				int tmp=min(p,arr[s[j].second]);
				p-=tmp;
				cnt-=tmp;
			}
			j++;
		}
	}
	cout<<MX+(cnt*2-p)<<'\n';
	return 0;
}

// Vaidik Patel(India)
// DA-IICT
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
int INF = (int)1e9;
ll INFINF = (ll)1e18 + 10;
const ld PI = 3.14159265358979323846;

#define precision(x,d) cout<<fixed<<setprecision(d)<<x
#define minQueue priority_queue<ll,vector<ll>,greater<ll> >
#define maxQueue priority_queue<ll,vector<ll>,less<ll> >

#define FOR(i,a,b) for(ll i=a;i<b;i++)
#define rFOR(i,a,b) for(ll i=a;i>=b;i--)
#define deb1(x) cout<<#x<<" : "<<x<<endl;
#define deb2(x,y) cout<<#x<<" : "<<x<<"\t"<<#y<<" : "<<y<<endl;
#define deb3(x,y,z) cout<<#x<<" : "<<x<<"\t"<<#y<<" : "<<y<<"\t"<<#z<<" : "<<z<<endl;
#define deb4(x,y,z,w) cout<<#x<<" : "<<x<<"\t"<<#y<<" : "<<y<<"\t"<<#z<<" : "<<z<<"\t"<<#w<<" : "<<w<<endl;
#define deb5(a, b, c, d, e)    cout<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl;
#define deb6(a, b, c, d, e, f) cout<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl;

#define fill(a,v) memset(a, v, sizeof (a)) // only for set 0 or -1 value in integer array
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()

#define checkbit(n,b) ( (n >> b) & 1)//

typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define M  1000000007
#define FIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define TIME cerr << "Time Elapsed : "<<1.0*clock()/CLOCKS_PER_SEC<<"\n";

ll powermodm(ll x,ll n,ll mod)
{ll result=1;while(n>0){if(n % 2 ==1)result=(result * x)%mod;x=(x*x)%mod;n=n/2;}return result;}
ll GCD(ll , ll );
ll LCM(ll ,ll);
ll power(int ,int);
ll choose(ll,ll);
int ones(ll);
void extendedEuclid(ll, ll);
ll MMI(ll, ll);
void fastscan(int &);
bool checkithbit(ll,ll); // ith bit is zero or not
//////////////////////////////////////////////////////////////////////////////
#define N 400005
int n,m;
int k[N],ktemp[N];
vector<int>day[N],daytemp[N];
int checkdays(int days)
{
    for(int i=1;i<=n;i++)
    {
        ktemp[i]=k[i];
    }
    vector<int>vis(N);

    for(int i=1;i<=days;i++)
    {
      for(auto it:day[i])
      {
          if(vis[it]==1)
          {
              continue;
          }
          else
          {
              daytemp[i].push_back(it);
          }
      }
    }
    int balance=0;
    for(int i=1;i<=days;i++)
    {
        balance++;
        if(daytemp[i].size()!=0)
        {

            for(auto it:daytemp[i])
            {

                int x=min(balance,ktemp[it]);
                ktemp[it]-=x;
                balance-=x;
            }

        }
    }
    int countremain=0;
    for(int i=1;i<=n;i++)
    {
        countremain+=ktemp[i];
    }
    if(2*countremain<=balance)
    {
        return 1;
    }
    else{return 0;}
}
int find(int s,int e)
{
    int mid,ans;
    while(s<=e)
    {
        m=(s+e)/2;
       // deb3(s,e,m);
        if(checkdays(m))
        {
            ans=m;
            e=m-1;
        }
        else
        {
            s=m+1;
        }
    }
    return ans;
}
int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>k[i];
    }
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        day[x].push_back(y);
    }
    int ans=find(1,N);

    cout<<ans<<endl;
    return 0;
}
//////////////////////////////////////////////////////////////////////////
bool checkithbit(ll a,ll i)
{
if(a & (1 << i))
{
return  true;
}
else
{
return false;
}
}
ll GCD(ll a , ll b)
{
    if(b==0)
        return a;
    else
        return GCD(b,a%b);
}
ll LCM(ll a,ll b){return (max(a,b)/GCD(a,b))*min(a,b);}

ll power(int a , int n)
{
    unsigned long long int result=1,x=a;
    while(n>0)
    {
        if(n % 2 ==1)
            result=result * x;
        x = x * x;
        n=n/2;
    }
    return result;
}
ll choose(ll n,ll k)
{
    if(k==0)  return 1;
    return (n* choose(n-1,k-1))/k;
}
int ones(ll n)
{
    int c=0;
    while(n)
    {
        n=n&(n-1);
        c++;
    }
    return c;
}
//store gcd of a,b in d
//store solution of a*x + b*y = d in x,y
// if gcd(a,b)=1 then x = a^(-1)(mod b) and y = b^(-1)(mod a)
ll d, x, y;
void extendedEuclid(ll A, ll B) {
    if(B == 0) {
        d = A;
        x = 1;
        y = 0;
    }
    else
    {
        extendedEuclid(B, A%B);
        int temp = x;
        x = y;
        y = temp - (A/B)*y;
    }
}
// return modulo inverse of a wrt modulo p(should be prime)
// retunt -1 if modulo inverse does not exist
ll MMI(ll a, ll p)
{
    extendedEuclid(a,p);
    if(d==1 && p!=1)
        return ((x%p)+p)%p;
    else
        return -1;
}

//Fastest way to read Input
void fastscan(int &number)
{
    bool negative = false;
    register int c;
    number = 0;
    c = getchar();
    if (c=='-')
    {
        negative = true;
        c = getchar();
    }
    for (; (c>47 && c<58); c=getchar())
        number = number *10 + c - 48;
    if (negative)
        number *= -1;
}
/*
note:
//a.resize(unique(a.begin(), a.end()) - a.begin()); use for create array unique element...
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); shuffle(g1.begin(), g1.end(), rng);(g1 is array name) for choose random number
//int grand(int x) {
    return uniform_int_distribution<int>(0, x - 1)(rng);
}
//use once(num) give no of 1 in its binary form
//use give (int)log2(num)+1 give no of digits in its binary form
//bitset<64>(num).to_string() convert decimal to num64 bit binary number
//stoull(str, nullptr, 2) convert str in binary form to decimal number
// "max" priority queue: priority_queue<ll, vector<ll>, less<ll> >pq;   #select max element as top()#
// "min" priority queue: priority_queue<ll, vector<ll>, greater<    ll> >pq; #select min element as top()#
*/

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> pii;

int n, m;
int arr[200200];
int last_promo[200200];

int main() {
    scanf("%d %d", &n, &m);

    int total_buy = 0;
    for (int i = 1; i <= n; i++){
        scanf("%d", &arr[i]);
        total_buy += arr[i];
    }

    int last_day = 0;
    for (int i = 0; i < m; i++) {
        int d, t;
        scanf("%d %d", &d, &t);
        last_promo[t] = max(last_promo[t], d);
        last_day = max(last_day, d);
    }

    int must_buy[200200];
    for (int i = 1; i <= n; i++) {
        // printf("HEHE %d %d %d\n", i, last_promo[i], arr[i]);
        must_buy[last_promo[i]] += arr[i];
    }

    int money = 0;
    int bought = 0;
    int ans = 2 * total_buy;
    for (int i = 0; i <= last_day; i++) {
        // printf("must buy [%d]: %d\n", i, must_buy[i]);
        if (money > must_buy[i]) {
            bought += must_buy[i];
            money -= must_buy[i];
        } else {
            bought += money;
            money = 0;
        }
        if (max(2 * (total_buy - bought)- money, 0) + i < ans)
            ans = max(2 * (total_buy - bought)- money, 0) + i;

        money++;
    }

    printf("%d\n", ans);

}

#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;
typedef pair<int, int> pii;
typedef double db;
const int N = 2e5 + 5;
vi mic[N];
int k[N], sale[2 * N];
int n, m, sum;

bool check(int mid)
{
	for (int i = 1; i <= mid; ++ i) sale[i] = 0;
	for (int i = 1; i <= n; ++ i)
	{
		auto it = upper_bound(all(mic[i]), mid);
		if(it == mic[i].begin()) continue;
		-- it;
		sale[*it] += k[i];
	}
	int re = 0, buy = 0;
	for (int i = 1; i <= mid; ++ i)
	{
		re ++;
		buy += min(re, sale[i]);
		re = re - min(re, sale[i]);
	}
	if(re >= (sum - buy) * 2) return 1;
	else return 0;
}
int main()
{
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; ++ i)
	{
		scanf("%d", &k[i]);
		sum += k[i];
	}
	for (int i = 1; i <= m; ++ i)
	{
		int d, t; scanf("%d%d", &d, &t);
		mic[t].pb(d);
	}
	int l = sum, r = sum * 2;
	while (l < r)
	{
		int mid = (l + r) >> 1;
		if(check(mid)) r = mid; else l = mid + 1;
	}
	printf("%d\n", l);
	return 0;
}

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

const int maxn= 2e5+2;
long long n, m, v[maxn], v1[maxn];

vector<long long>G[maxn];

bool solve(long long x)
{
    vector<pair<long long, long long> >R;
    memcpy(v1, v, sizeof v);
    for(int i=1; i<=n; i++)
    {
        if(G[i].size()!=0&&G[i][0]<=x)
        {
            int st=0, res=0, dr=G[i].size()-1;
            while(st<=dr)
            {
                int mid=(st+dr)/2;
                if(G[i][mid]<=x)
                {
                    res=mid;
                    st=mid+1;
                }
                else
                {
                    dr=mid-1;
                }
            }
            //reduc[i]=G[i][res];
            R.push_back({G[i][res], i});
        }
    }
    sort(R.begin(),R.end());
    long long ruble=0, prev=0;
    for(auto it:R)
    {
        ruble=ruble+it.first-prev;
        prev=it.first;
        long long cate = min(v1[it.second], ruble);
        ruble=ruble-cate;
        v1[it.second]=v1[it.second]-cate;
    }
    ruble=ruble+x-prev;
    long long total=0;
    for(int i=1; i<=n; i++)
    {
        total=total+v1[i];
    }
    if(2*total<=ruble)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    int x, y;
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        cin>>v[i];
    }
    for(int i=1; i<=m; i++)
    {
        cin>>x>>y;
        G[y].push_back(x);
    }
    long long st=1, dr=2000, res;
    while(st<=dr)
    {
        long long mid=(st+dr)/2;
        if(solve(mid))
        {
            res=mid;
            dr=mid-1;
        }
        else
        {
            st=mid+1;
        }
    }
    cout<<res;
    return 0;
}

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

using namespace std;

int n, m;
int list[1017];
int now[1017];
int sales[1017];

int test(int days){
    for(int i = 1; i <= n; i++) now[i] = list[i];
    //printf("\n## days = %d ", days);
    int balance = 0;
    for(int d = 1; d <= days; d++){
        balance ++;
        for(int i = 1; i <= n; i++){
            if(d == sales[i])
                while(balance > 0 && now[i]){
                    now[i] --;
                    balance --;
                }
        }
    }
    for(int i = 1; i <= n; i++){
        while(now[i] && balance >= 2){
            now[i] --;
            balance -= 2;
        }
        if(now[i] && balance < 2)
            return 0;
    }
    return 1;
}

int search(int l, int r){
    int mid = (l + r) >> 1;
    //printf("mid = %d ", mid);
    while(l < r){
        //printf("test(%d):%d\n", mid, test(mid));
        if(test(mid)) return search(l, mid);
        else return search(mid + 1, r);
    }
    return mid;
}

int main(){
    cin >> n >> m;
    int tot = 0;
    for(int i = 1; i <= n; i++){
        cin >> list[i];
        tot += list[i];
    }
    int t, d;
    for(int i = 1; i <= m; i++){
        cin >> d >> t;
        sales[t] = max(sales[t], d);
    }
    int ans = search(1, 2 * tot + 2);
    cout << ans << endl;
}

#include<bits/stdc++.h>
#define int long long
#define pb push_back
#define fi first
#define se second
#define pii pair<int,int>
#define mp make_pair
using namespace std;
void solve(){
    int n,m;
    cin>>n>>m;
    int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    vector<pii > v;
    for(int i=0;i<m;i++){
        int x,y;
        cin>>x>>y;
        y--;
        v.pb(mp(x,y));
    }
    sort(v.begin(),v.end());
    int l=0,r=INT_MAX;
    int ans=INT_MAX;
    while(l<=r){
        int mid = (l+r)/2;
        int cnt=0;
        int last=-1;
        for(int i=0;i<m;i++){
            if(v[i].fi<=mid){
                last=i;
            }
        }
        int b[n];
        for(int i=0;i<n;i++){
            b[i]=a[i];
        }
        for(int i=0;i<=last;i++){
            int x = v[i].fi;
            int y = v[i].se;
            x-=cnt;
            if(x<=0){
                continue;
            }
            cnt+=min(x,b[y]);
            b[y]-= min(x,b[y]);
        }
        int burles=mid-cnt;
        for(int i=0;i<n;i++){
            burles-= (2*b[i]);
        }
        if(burles<0){
            l=mid+1;
        }else{
            ans=mid;
            r=mid-1;
        }
        if(n==1000){
            cout<<mid<<" "<<burles<<endl;
        }
    }
    cout<<ans;
}
int32_t main()
{
    ios_base::sync_with_stdio(NULL);
    cin.tie(NULL);
    cout.tie(NULL);
    int t=1;
    while(t--){
        solve();
    }
}

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

const int N = 2e5+10;
int n, m;
int amount[N], amountCopy[N];
pair<int, int> sales[N];//day, item type

bool possible(int day) {
    int cnt = 0;
    for(int i = 1; i <= n; ++i) {
        cnt += amount[i];
        amountCopy[i] = amount[i];
    }
    if(cnt > day) return false;
    if(2*cnt <= day) return true;
    int singles = 0;
    int prevDay = 0;
    int money = 0;
    for(int i = 1; i <= m; ++i) {
        const int saleDay = sales[i].first;
        const int type = sales[i].second;
        if(saleDay > day) break;
        money += saleDay-prevDay;
        prevDay = saleDay;
        int numSingles = min(money, amountCopy[type]);
        //numSingles = min(numSingles, 1ll);
        singles += numSingles;
        money -= numSingles;
        amountCopy[type] -= numSingles;
    }
    money += day-prevDay;
    return (singles + 2*(cnt-singles) <= day);
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    int sum = 0;
    for(int i = 1; i <= n; ++i) {
        cin >> amount[i];
        sum += amount[i];
    }
    if(sum == 0) {
        cout << 0 << '\n';
        return 0;
    }
    for(int i = 1; i <= m; ++i) {
        cin >> sales[i].first >> sales[i].second;
    }
    sort(sales+1, sales+1+m);
    int start = -1, end = N*2, mid;
    while(start+1 < end) {
        mid = (start+end)/2;
        if(possible(mid)) end = mid;
        else start = mid;
    }
    cout << end << endl;
}

#include <iostream>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
using namespace std;
typedef long long ll;
#define vec vector
#define ms multiset
#define pb push_back
#define pll pair<long long, long long>
#define pii pair<int, int>
#define vi vector<int>
#define vll vector<long long>
#define int long long
#define _ << " " <<
#define all(a) a.begin(), a.end()
#define srt(a) std::sort(a.begin(), a.end())
template<typename T>
vector<T> _set_to_vec(std::set<T> z)
{
	vector<T> w;
	auto it = z.begin();
	while (it != z.end())
		w.push_back(*it++);
	return w;
}
template<typename T>
void pop_front(std::vector<T>& vec)
{
	vec.erase(vec.begin());
}

vector<long long> z_function(string s) {
	long long n = (long long)s.length();
	vector<long long> z(n);
	for (long long i = 1, l = 0, r = 0; i < n; ++i) {
		if (i <= r)
			z[i] = min(r - i + 1, z[i - l]);
		while (i + z[i] < n && s[z[i]] == s[i + z[i]])
			++z[i];
		if (i + z[i] - 1 > r)
			l = i, r = i + z[i] - 1;
	}
	return z;
}
struct point {
	double x, y;
	point(double x, double y) :x(x), y(y) {};
	point() {};
};

point operator+(point a, point b) { return point(a.x + b.x, a.y + b.y); };
point operator-(point a, point b) { return point(a.x - b.x, a.y - b.y); };
double operator*(point a, point b) { return (a.x * b.x + a.y * b.y); };

double operator^(point a, point b) { return (a.x * b.y - a.y * b.x); };
double operator%(point a, point b) { return atan2(a ^ b, a * b); }
double eps = 1e-13;
template<typename T>
bool equals(T a, T b)
{
	return abs(a - b) <= eps;
}
template<typename T>
int sign(T a)
{
	return a < 0 ? -1 : (a > 0 ? 1 : 0);
}
#define pt point
inline double area(pt a, pt b, pt c) {
	return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
inline char intersect_1(double a, double b, double c, double d) {
	if (a > b)  swap(a, b);
	if (c > d)  swap(c, d);
	return max(a, c) <= min(b, d);
}

char intersect(pt a, pt b, pt c, pt d) {
	return intersect_1(a.x, b.x, c.x, d.x)
		&& intersect_1(a.y, b.y, c.y, d.y)
		&& area(a, b, c) * area(a, b, d) <= 0
		&& area(c, d, a) * area(c, d, b) <= 0;
}

double pi = acos(-1.0);
double dist(point p)
{
	return sqrt(p.x * p.x + p.y * p.y);
}

bool cmpr(pt a, pt b)
{
	if (equals((a ^ b), (double)0))
		return dist(a) < dist(b);
	else return (a ^ b) < 0;
}
bool cmp(pt a, pt b) {
	return a.x < b.x || a.x == b.x && a.y < b.y;
}

bool cw(pt a, pt b, pt c) {
	return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < 0;
}

bool ccw(pt a, pt b, pt c) {
	return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0;
}

void convex_hull(vector<pt>& a) {
	if (a.size() == 1)  return;
	sort(a.begin(), a.end(), &cmp);
	pt p1 = a[0], p2 = a.back();
	vector<pt> up, down;
	up.push_back(p1);
	down.push_back(p1);
	for (size_t i = 1; i < a.size(); ++i) {
		if (i == a.size() - 1 || cw(p1, a[i], p2)) {
			while (up.size() >= 2 && !cw(up[up.size() - 2], up[up.size() - 1], a[i]))
				up.pop_back();
			up.push_back(a[i]);
		}
		if (i == a.size() - 1 || ccw(p1, a[i], p2)) {
			while (down.size() >= 2 && !ccw(down[down.size() - 2], down[down.size() - 1], a[i]))
				down.pop_back();
			down.push_back(a[i]);
		}
	}
	a.clear();
	for (size_t i = 0; i < up.size(); ++i)
		a.push_back(up[i]);
	for (size_t i = down.size() - 2; i > 0; --i)
		a.push_back(down[i]);
}

typedef string str;

template<typename T>
inline istream& operator >>(istream& in, vec<T>& a) {
	for (int i = 0; i < a.size(); i++) in >> a[i];
	return in;
}

template<typename T>
inline ostream& operator <<(ostream& out, vec<T>& a) {
	for (int i = 0; i < a.size(); i++) out << a[i] << " ";
	return out;
}

template<typename T, typename E>
inline istream& operator >>(istream& in, pair<T, E>& a) {
	in >> a.first >> a.second;
	return in;
}

template<typename T>
T gcd(T a, T b) {
	T c;
	while (b) {
		c = a % b;
		a = b;
		b = c;
	}
	return a;
}

template<typename T>
T lcm(T a, T b) {
	return (a / gcd(a, b)) * b;
}

vector<int> prefix_function(string s) {
	int n = (int)s.length();
	vector<int> pi(n);
	for (int i = 1; i < n; ++i) {
		int j = pi[i - 1];
		while (j > 0 && s[i] != s[j])
			j = pi[j - 1];
		if (s[i] == s[j])  ++j;
		pi[i] = j;
	}
	return pi;
}

int binpow(int a, int n) {
	if (n == 0)
		return 1;
	if (n & 1)
		return binpow(a, n - 1) * a;
	else {
		int b = binpow(a, n >> 1);
		return b * b;
	}
}

vector<int> primes(int N) {
	vector<int> lp(N + 1);
	vector<int> pr;

	for (int i = 2; i <= N; ++i) {
		if (lp[i] == 0) {
			lp[i] = i;
			pr.push_back(i);
		}
		for (int j = 0; j < (int)pr.size() && pr[j] <= lp[i] && i * pr[j] <= N; ++j)
			lp[i * pr[j]] = pr[j];
	}
	return pr;
}

typedef vec<vi> matrix;

matrix operator*(matrix& a, matrix& b) {
	matrix m;
	int cx = a[0].size(), cy = b.size();
	m.resize(cx);
	for (int i = 0; i < cx; i++)
		m[i].resize(cy);
	for (int i = 0; i < cx; i++) {
		for (int j = 0; j < cy; j++) {
			int res = 0;
			for (int p = 0; p < b[0].size(); p++)
				res += a[i][p] * b[p][j];
			m[i][j] = res;
		}
	}
	return m;
}

int cnt = 0;
matrix pow(matrix& a, int b) {
	if (b == 1)
		return a;
	cnt++;
	if (b & 1)
	{
		auto r = pow(a, b - 1);
		r = r * a;
		return r;
	}
	else {
		auto r = pow(a, b / 2);
		r = r * r;
		return r;
	}
}
set<int> printDivisors(int n)
{
	set<int> r;
	// Note that this loop runs till square root
	for (int i = 1; i <= sqrt(n); i++)
	{
		if (n % i == 0)
		{
			// If divisors are equal, print only one
			if (n / i == i)
				r.insert(i);

			else // Otherwise print both
				r.insert(i), r.insert(n / i);
		}
	}
	return r;
}

int n, m, s = 0;
vi a;
map<int, vector<int>> mp;

inline bool check(int k) {
	auto aa = a;
	int bal = k;
	for (int i = k; i; i--) {
		if (mp.count(i)) {
			int w = 0;
			k = min(k, i);
			for (auto e : mp[i]) {
				bal -= min(k, aa[e]);
				int ww = a[e];
				aa[e] -= min(k, aa[e]);
				k -= min(k, ww);
			}
		}
	}
	int cnt = 0;
	for (int i = 0; i < n; i++)
		cnt += aa[i];
	return cnt * 2 <= bal;

}

inline void solve() {
	cin >> n >> m;
	a.resize(n);
	cin >> a;
	for (int i = 0; i < n; i++) s += a[i];
	set<pii> b;
	for (int i = 0; i < m; i++) {
		int u, l;
		cin >> u >> l;
		b.insert({ u, l - 1 });
	}
	for (auto e : b)
		mp[e.first].pb(e.second);

	int l = 0, r =1+( s << 1);
	while (l < r - 1) {
		int m = (l + r) / 2;
		if (check(m))
			r = m;
		else
			l = m + 1;
	}
	cout << r;
}

int32_t main() {
	ios::sync_with_stdio(false);
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	solve();
	int k;
	cin >> k;
}

#include "bits/stdc++.h"

using namespace std;
int a[200004];
vector<int> b[400004];
int c[400004];int n,m,sum;
bool che (int mid )
{
    int num=sum;
    for (int i = 1; i <= n; ++i) {
        c[i]=a[i];
    }
    int left = mid;
    int x=0;
    for (int i = mid; i >=1 && left; --i) {
        if(left>i)
        {
            x+=left-i;
            left=i;
        }
        for (int j = 0; j < b[i].size(); ++j) {
            if(!c[b[i][j]])continue;
            int temp = min(c[b[i][j]],left);
            c[b[i][j]] -= temp;
            num-=temp;
            left-=temp;
        }
    }
    return x>=num*2;
}
int main() {

    cin>>n>>m;
    for (int i = 1; i <= n; ++i) {
        scanf("%d",&a[i]);
        sum+=a[i];
    }
    int d,t;
    for (int i = 0; i < m; ++i) {
        scanf("%d%d",&d,&t);
        b[d].push_back(t);
    }
    int l = 1,r=sum*2;
    int ans = -1;
    while(l<=r)
    {
        int mid = (l+r)>>1;
        if(che(mid)){
            ans=mid;
            r=mid-1;
        }
        else l=mid+1;
    }
    cout<<ans<<endl;
}

/*author:anshumanc007
created on: birthday'19*/
//Everybody's gangster until the real ganster walks in !
#include <bits/stdc++.h>
#include <queue>
#include <stack>
using namespace std;
typedef pair<long long int,long long int>pa;
#define pb push_back
long long int MAX= 200005;
long long int MOD=998244353;
long long int INF=1e18;

//1165F
int main()
{
       ios_base::sync_with_stdio(false);
       cin.tie(NULL);
       cout.tie(NULL);
       long long int i,j,k=0,l=0,r=0,m=0,n,b,c,a,p=0,cnt=0,cnt1=0,x,y,z,low,mid,high,ans=0,maxi=0,mini=INF,t,sum;
       string s;
    cin>>n>>m;
    long long int A[MAX+1];
    vector<long long int>D[MAX+1];
    for(i=1;i<=n;i++)
    {
        cin>>A[i];
        l=l+A[i];
    }
    for(i=0;i<m;i++)
    {
        cin>>x>>y;
        D[x].pb(y);
    }
    long long int B[MAX+1];
    low=1;
    high=2*l;
    ans=high;
    while(low<=high)
    {
       mid=(low+high)/2;
        l=0;
     for(i=1;i<=n;i++)
     {
         B[i]=A[i];
         l=l+A[i];
     }

        t=1;
        l=2*l;
       for(j=1;j<=min(mid,MAX);j++)
        {

            for(k=0;k<D[j].size();k++)
            {
                    p=D[j][k];
                    r=min(B[p],t);
                     B[p]=B[p]-r;
                     l=l-r;
                    t=t-r;
                    //cout<<r<<" ";
                }

            t++;
            }

     if(l<=mid)
     {
         ans=min(ans,mid);
         high=mid-1;
     }
     else
     {
         low=mid+1;
     }
    // cout<<mid<<endl;
    }
    cout<<ans<<endl;

}

/*
 * 	Roses are red
 * 		Violets are blue
 * 			I cried
 * 				And so did you
 */
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#ifndef rd
#define endl '\n'
#endif
#ifdef rd
#define trace(...) cout<<"Line:"<<__LINE__<<" "; __f(#__VA_ARGS__, __VA_ARGS__)
template<typename Arg1>
void __f(const char* name, Arg1&& arg1) {
	cout<<name<<" : "<<arg1<<endl;
}
template<typename Arg1, typename ... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
	const char* comma=strchr(names+1,',');
	cout.write(names,comma-names)<<" : "<<arg1<<" | ";
	__f(comma+1,args...);
}
#else
#define trace(...)
#endif
#define pb push_back
#define fi first
#define se second
#define int long long
typedef long long ll;
typedef long double f80;
#define double long double
#define pii pair<int,int>
#define pll pair<ll,ll>
#define sz(x) ((long long)x.size())
#define fr(a,b,c) for(int a=b; a<=c; a++)
#define rep(a,b,c) for(int a=b; a<c; a++)
#define trav(a,x) for(auto &a:x)
#define all(con) con.begin(),con.end()
const ll infl=2e18;
const int infi=1e9;
//const int mod=998244353;
const int mod=1000000007;
typedef vector<int> vi;
typedef tree<int, null_type, less<int>, rb_tree_tag,
		tree_order_statistics_node_update> oset;
mt19937 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
auto clk=clock();
int rng(int lim) {
	uniform_int_distribution<int> uid(0,lim-1);
	return uid(rang);
}

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

int k[200005];
int need[200005];
vector<int> offers[400005];
void solve() {
	int n,m;
	cin>>n>>m;
	int sum=0;
	fr(i,1,n) {
		cin>>k[i];
		sum+=k[i];
	}
	if(k[1]==0&&k[2]==0) {
		cout<<sum<<endl;
		exit(0);
	}
	int d,t;
	fr(i,1,m) {
		cin>>d>>t;
		offers[d].pb(t);
	}
	int lo=1,hi=400000,mid=(lo+hi)/2;
	while(lo<hi) {
		int burle=mid,excess=0;
		fr(i,1,n)
			need[i]=k[i];
		for(int i=mid; i>0&&burle; i--) {
			if(burle>i) {
				excess++;
				burle--;
			}
			for(int j:offers[i]) {
				if(need[j]) {
					if(burle>need[j]) {
						burle-=need[j];
						need[j]=0;
					} else {
						need[j]-=burle;
						burle=0;
						break;
					}
				}
			}
		}
		int rem=0;
		fr(i,1,n) {
			rem+=need[i];
		}
		if(2*rem<=excess) {
			hi=mid;
		} else
			lo=mid+1;
		mid=(lo+hi)/2;
	}
	cout<<mid<<endl;
}

signed main() {
	ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	srand(chrono::high_resolution_clock::now().time_since_epoch().count());
	cout<<fixed<<setprecision(10);
	int t=1;
//	cin>>t;
	while(t--)
		solve();
#ifdef rd
	cout<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
	return 0;
}

#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef pair <int, int> pii;

int n, m, l, r, mid, mx, a[200005];
pii b[200005];
bool sale[200005];

bool ok(int p) {
	int last = 0, cre = p, cnt = 0, mos, e = 0, c[200005];
	for (int i = 1; i <= n; i++) c[i] = a[i - 1];
	while (e < m && b[e].fi <= p) e++;
	for (int i = e - 1; i >= 0; i--) {
		cre = min(cre, b[i].fi);
//		cout << ">> " << b[i].fi << ' ' << cre << ' ' << b[i].se << ' ' << c[b[i].se] << endl;
		mos = min(cre, c[b[i].se]);
//		cout << mos << endl;
		c[b[i].se] -= mos, cre -= mos, cnt += mos;
	}
//	cout << cnt << endl;
	for (int i = 1; i <= n; i++) {
		cnt += c[i] * 2;
	}
//	cout << p << ' ' << cnt << endl;
	return (cnt <= p);
}

int main() {
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
		mx += a[i];
	}
	for (int i = 0; i < m; i++) {
		cin >> b[i].fi >> b[i].se;
	}
	sort(b, b + m);
//	for (int i = 0; i < m; i++) cout << b[i].fi << ' ' << b[i].se << endl;/
	r = mx * 2;
	for (int i = 20; i > 0; i--) if (r > 1 << i && ok(r - (1 << i))) r -= i;
	cout << r - 1 << endl;
}

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#define N 200005
using namespace std;
typedef long long ll;
const ll mod = 998244353LL;
int n, m;
int k[N];
int cnt[N];
vector<int> ss[N];
int main() {
  cin>>n>>m;
  int tot=0;
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &k[i]);
    tot += k[i];
  }
  set<pair<int,int>> st;
  st.clear();
  for (int i = 1; i <= m; ++i) {
    int d, t;
    scanf("%d%d", &d, &t);
    st.insert(make_pair(d, t));
  }
  vector<pair<int,int>> sv(st.begin(), st.end());
  memset(cnt, 0, sizeof(cnt));
  for (int i = 0; i < sv.size(); ++i) {
    int d = sv[i].first;
    int t = sv[i].second;
    ss[d].push_back(t);
    cnt[t]++;
  }
  int cur=0;
  for (int i = 1; i <= 200000; ++i) {
    cur++;
    vector<pair<int, int>> rk;
    for (int j = 0; j < ss[i].size(); ++j) {
      rk.push_back(make_pair(cnt[ss[i][j]], ss[i][j]));
    }
    sort(rk.begin(), rk.end());
    for (int j = 0; j < rk.size(); ++j) {
      int t = rk[j].second;
     // if (i==1) cout<<"j="<<j<<" "<<t<<" "<<k[t]<<endl;
      if (cur >= k[t]) {
        cur -= k[t];
        tot -= k[t];
        k[t] -= k[t];
      } else {
        k[t] -= cur;
        tot -= cur;
        cur -= cur;
        break;
      }
    }
    if (cur >= 2*tot) {
      cout<<i<<endl;
      return 0;
    }
   // cout<<i<<" "<<cur<<" "<<tot<<endl;
    for (int j = 0; j < rk.size(); ++j) {
      int t = rk[j].second;
      cnt[t]--;
    }
  }
  cout<<200001<<endl;
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
struct day { int d, t; };
bool operator < (const day &a, const day &b)
{
	return a.d < b.d;
}
int main()
{
	int n, m;
	cin >> n >> m;
	vector<int>a(n);
	for (int i = 0; i < n; i++)
		cin >> a[i];
	vector<day>b(m);
	for (int i = 0; i < m; i++)
		cin >> b[i].d >> b[i].t;
	sort(b.begin(), b.end());
	int l = 1, r = 2000, ans = 0;
	for (int i = 0; i < n; i++)
		ans += a[i] * 2;
	while (l <= r)
	{
		int mid = (l + r) / 2;
		int i = m - 1;
		for (; i >= 0; i--)
			if (mid >= b[i].d)
				break;
		int mon = mid;
		vector<int>tmp(n);
		for (int i = 0; i < n; i++)
			tmp[i] = a[i];
		for (int k = mid; k > 0 && i >= 0 && mon > 0;)
		{
			if (k == b[i].d)
			{
				int res = mon;
				for (; i >= 0 && mon > 0 && k == b[i].d; i--)
				{
					int ge = min(mon, tmp[b[i].t - 1]);
					mon -= ge, tmp[b[i].t - 1] -= ge;
				}
				k--;
			}
			else if (i >= 0 && b[i].d > k)
				for (; i >= 0 && b[i].d > k; i--);
			else
				k--;
			if (mon > k)
				mon--;
		}
		int total = 0;
		for (int i = 0; i < n; i++)
			total += (a[i] - tmp[i]) + tmp[i] * 2;
		if (total <= mid)
		{
			if (total == mid)
				ans = min(ans, mid);
			if (l == r)
				break;
			else
				r = mid;
		}
		else if (total > mid)
		{
			if (l == r)
				break;
			else
				l = mid + 1;
		}
	}
	cout << ans;
	return 0;
}

#include<bits/stdc++.h>

using namespace std;

#define ff first
#define ss second

int main()
{
    int n,m;
    cin >> n >> m;
    int a[n];
    long long int sum=0;
    for(int i=0;i<n;i++)
    {
        cin >> a[i];
        sum+=a[i];
    }
    pair<int,int> b[m];
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin >> x >> y;
        b[i]=make_pair(x,y);
    }
    int late[n]={0};
    sort(b,b+m);
    for(int i=0;i<m;i++)
    {
        late[b[i].ss]=b[i].ff;
    }
    /*for(int i=0;i<m;i++)
        cout << b[i].ff << " ";
    cout << endl;*/
    long long int low=0,high=2*sum,ans=0;
    while(low<=high)
    {
        long long int mid=(high+low)/2,t=sum,t2=0;
        int j=0,pre=0;
        int d[n];
        for(int i=0;i<n;i++)
            d[i]=a[i];
        for(int i=0;i<m&&b[i].ff<=mid;i++)
        {
            if(late[b[i].ss]!=b[i].ff)
                continue;
            j+=b[i].ff-pre;
            t-=min(d[b[i].ss-1],j);
            int t1=d[b[i].ss-1];
            d[b[i].ss-1]-=min(d[b[i].ss-1],j);
            j=max(0,j-t1);
            t2=mid-b[i].ff;
            pre=b[i].ff;
            //cout << b[i].ff << " " << t << endl;
        }
        j+=t2;
        if(2*t<=j)
        {
            ans=mid;
            high=mid-1;
        }
        else
            low=mid+1;
    }
    if(ans==0)
        cout << sum;
    cout << ans;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define fr(i,j,n) for(i=j;i<n;i++)
#define frd(i,j,n) for(i=n-1;i>=j;i--)
#define flash ios_base::sync_with_stdio(false); cin.tie(NULL),cout.tie(NULL);
#define tc int tc; cin>>tc; while(tc--)
#define endl "\n"
#define pb push_back
#define mp make_pair
#define vc vector
#define vl vector<ll>
#define pr pair<ll,ll>
#define vp vector<pr>
#define all(v) v.begin(),v.end()
#define srt(v) sort(all(v))
#define srtd(v) sort(v.rbegin(),v.rend())
#define F first
#define S second
vl d[200005];
int main()
{
    flash
    #ifndef ONLINE_JUDGE
    freopen("inp","r",stdin);
    #else
    // online submission
    #endif

    ll n,m,i,k,x,y;
    cin>>n>>m;
    ll a[n];
    fr(i,0,n)
    cin>>a[i];
    vp v;
    fr(i,0,m){
      cin>>x>>y;
      v.pb(mp(x,y));
    }
    srt(v);
    for(auto p:v){
      x=p.F;
      y=p.S;
      d[y].pb(x);
    }
    ll b,an;
    ll l=1,r=2*n+1,mid,ans,t;
    while(l<=r){
      v.clear();
      mid=(l+r)/2;
    //  cout<<l<<" "<<r<<" "<<mid<<endl;
      fr(i,1,n+1){
        k=1000000007;
        for(auto z:d[i]){
          if(z>mid)
          break;
          k=z;
        }
        v.pb(mp(k,i));
      }
      srt(v);
      b=0;
      an=0;
      k=0;
      for(auto p:v){

        x=p.F;
        y=p.S;
        if(x==1000000007){
          an+=(2*a[y-1]);
          continue;
        }
        b+=(x-k);
        if(a[y-1]<=b){
          b-=a[y-1];
          an+=a[y-1];
        }
        else{
          t=a[y-1]-b;
          an+=b;
          b=0;
          an+=(2*t);
        }
        k=x;

      }
      ans=an;
      if(an>mid){
        l=mid+1;
      }
      else{
        r=mid-1;
      }
    }
    cout<<ans;
    return 0;
}

#include <bits/stdc++.h>

#define db(x) cerr << #x ": " << (x) << '\n';

using namespace std;

typedef long long ll;

typedef long double ld;

typedef pair<int,int> pii;

const int oo = 1e9;

const int MAXN = 5e5 + 100;

int N, M;

int A[MAXN];

vector<pii> vect;

int last[MAXN];

int sum = 0;

bool f(int mid)
{
    for(int i = 0 ; i < MAXN ; i++)last[i] = -1;
    for(int i = 0 ; i < vect.size() ; i++)
    {
        if(vect[i].second > mid)continue;
        last[vect[i].second] = vect[i].first;
    }
    int arr[MAXN];
    for(int i = 0 ; i < MAXN ; i++)arr[i] = 0;
    for(int i = 1 ; i <= N ; i++)
    {
        if(last[i] != -1)arr[last[i]] += A[i];
    }
    int cont = 0;
    for(int i = 1 ; i <= mid ; i++)
    {
        cont++;
        while(cont && arr[i])cont--,arr[i]--;
    }
    int gasto = mid-cont;
    int falta = sum-gasto;
    if(falta*2<=cont)
    {
        return true;
    }
    else
    {
        return false;
    }
}

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

    cin >> N >> M;

    for(int i = 1 ; i <= N ; i++)
    {
        cin >> A[i];
        sum += A[i];
    }

    for(int i = 1 ; i <= M ; i++)
    {
        int d, t;
        cin >> d >> t;
        vect.push_back({d,t});
    }

    sort(vect.begin(),vect.end());

    for(int i = 1 ; i < MAXN ; i++)
    {
        if(f(i))
        {
            cout << i << '\n';
            return 0;
        }
    }

//    int a = 1, b = MAXN;
//    int res = -1;
//    while(a <= b)
//    {
//        int mid = (a+b)/2;
//        if(f(mid))
//        {
//            b = mid-1;
//            res = mid;
//        }
//        else
//        {
//            a = mid+1;
//        }
//    }

    //cout << res << '\n';

    return 0;
}

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <random>
#include <ctime>
#include <string>
#include <iomanip>
#include <set>
#include <map>
#include <queue>
#include <numeric>
#include <limits>
#include <fstream>
#include <stack>
#include <unordered_set>
#include <sstream>
#include <array>
#include <chrono>
#include <unordered_map>
#include <cassert>

using namespace std;

typedef unsigned long long uli;
typedef long long li;
typedef long double ld;
typedef pair<int, int> pii;
typedef vector<int> vi;

#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
//#define x first
//#define y second
#define pb push_back
#define mp make_pair
#define forn(i, n) for(int i = 0; i < int(n); ++i)
#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)
#define forb(i, n) for(int i = int(n) - 1; i >= 0; --i)
#define left 2 * v + 1
#define right 2 * v + 2

const int INF = 1e9 + 1000;
const li INF64 = 1e18;

const int N = 4e5 + 1000;
const int MOD = 998244353;
const double EPS = 1E-9;
const double PI = acos(-1.);

li gcd(li a, li b) {
	return a == 0 ? b : gcd(b % a, a);
}

vector<pii> t;
vector<int> k;
vector<int> lasts;
vector<vector<int>> nxt;
int n;

bool ok(int day) {
	int money = 0;

	vector<int> need = k;
	vector<int> poses(n, 0);
	int last = 0;

	for (auto e : t) {
		money += e.first - last;
		last = e.first;

		int type = e.second;
		int curidx = poses[type];
		poses[type]++;
		if (curidx + 1 < nxt[type].size() && nxt[type][curidx] <= day) {
			continue;
		}

		if (need[e.second]) {
			assert(need[e.second] == k[e.second]);

			if (money >= need[e.second]) {
				money -= need[e.second];
				need[e.second] = 0;
			}
			else {
				need[e.second] -= money;
				money = 0;
			}
		}
	}

	money += day - last;
	int rest = 0;
	for (auto i : need) {
		rest += i * 2;
	}

	return money >= rest;

}

int main() {

#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int m;
	cin >> n >> m;

	int l = 0, r = 1e9;
	k.resize(n);
	t.resize(m);

	for (auto& i : k) {
		cin >> i;
	}

	for (auto& i : t) {
		cin >> i.first >> i.second;
		i.second--;
	}

	sort(all(t));

	lasts.resize(n, INF);
	nxt.resize(n);

	for (auto e : t) {

		int d = e.first;
		int t = e.second;

		nxt[t].push_back(d);
	}

	while (r - l > 1) {
		int m = (r + l) / 2;
		if (ok(m))
			r = m;
		else
			l = m;
	}

	cout << r;

}

#include <bits/stdc++.h>

using namespace std;

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

    int n, m;
    cin >> n >> m;
    vector<int> k(n);
    for (int i = 0; i < n; ++i) {
        cin >> k[i];
    }
    vector<vector<int>> off(n);
    for (int i = 0; i < m; ++i) {
        int d, t;
        cin >> d >> t;
        --d;
        --t;
        off[t].push_back(d);
    }
    constexpr int INF = 400'001;
    int low = 0, high = INF, ans = INF;
    while (low <= high) {
        int mid = (low + high) / 2;
        vector<pair<int, int>> cur_off;
        for (int i = 0; i < n; ++i) {
            // get last offer thats in [0, mid) for each type
            auto it = lower_bound(begin(off[i]), end(off[i]), mid);
            if (it != begin(off[i])) {
                cur_off.emplace_back(*--it, i);
            }
        }
        sort(begin(cur_off), end(cur_off));
        vector<int> cur_k(k);
        int cur_money = 1, cur_d = 0;
        for (const auto &[d, t] : cur_off) {
            // try to use last offers in order of days
            cur_money += (d - cur_d);
            cur_d = d;
            int cnt = min(cur_k[t], cur_money);
            cur_k[t] -= cnt;
            cur_money -= cnt;
        }
        cur_money += (mid - cur_d);
        for (int i = 0; i < n; ++i) {
            // buy types unsatisfied by offers on the last day (mid)
            cur_money -= cur_k[i] * 2;
        }
        if (cur_money >= 0) {
            high = mid - 1;
            ans = mid;
        } else {
            low = mid + 1;
        }
    }
    cout << ans + 1 << "\n";

    return 0;
}

 #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
    #define pb push_back
    #define sz(a) ll((a).size())
    #define   pr  pair<ll,ll>
    #define all(c) (c).begin(),(c).end()
    #define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
    #define SIZE 100002
    #define fi first
    #define se  second
    #define vi vector<ll>
    #define hell  998244353
#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>
    #define MAXN 1000000+1000
  //  #define M_PI      3.14159265358979323846
    using namespace std;

      typedef  long long int ll ;

   using namespace __gnu_pbds;
   ll n,m;
     ll total=0;
   vector<ll> day[2000009];
  ll conti[2000009];
   bool check(ll x){
    ll arr[n];
    ll fin=0;
    for(ll i=0;i<n;++i) arr[i]=conti[i];
    ll bal=0;
    for(ll i=1;i<=x;++i){
      bal++;
      if(!day[i].empty()){
        for(ll j=0;j<day[i].size();++j){
          ll x= day[i][j];
          ll mm= min(bal,arr[x]);
          bal-=mm;
          arr[x]-=mm;
          fin+=mm;
        }
      }

        if(fin==total){return true;}
    //cout<<fin<<"^"<<bal<<"&";
    }
    if(fin!=total){
      if(2*(total-fin)<=bal) return true;
      else return false;
    }
    else return true;

   }

    void machayenge(){
      cin>>n>>m;
      total=0;
      for(ll i=0;i<n;++i){
       cin>>conti[i];
        if(conti[i]) total+=conti[i];
      }
      for(ll i=0;i<m;++i){
        ll t,d; cin>>d>>t;
        d;t--;
        day[d].push_back(t);

      }

      ll i=1,j=2*total;
     // cout<<total;
      while(i<j){
        ll mid= (i+j)/2;
        if(check(mid)){
          j=mid;
        }
        else i=mid+1;
        //cout<<i<<" "<<j<<"&";
      }
    //  cout<<check(8);
      cout<<i;return ;

   }

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

//    cout<<5%3;
 machayenge();

    return 0;}

#include <bits/stdc++.h>

#define ll long long

using namespace std;

template <typename T>
void sort_and_uniq(vector<T> & A) {
    sort(A.begin(), A.end());
    A.erase(unique(A.begin(), A.end()), A.end());
}

int main() {
    using namespace std;
    ll n, m, a, b, c, s;
    cin >> n >> m;
    vector<ll> A(n + 1, 0);
    const int max_day = 200'000;
    vector< vector<int> > item_sales(n + 1), day_sales(max_day + 1);
    for(int i = 1; i <= n; i++) cin >> A[i];
    s = accumulate(A.begin(), A.end(), 0);

    for(int i = 0; i < m; i++) {
        cin >> a >> b;
        item_sales[b].push_back(a);
        day_sales[a].push_back(b);
    }

    for(int i = 0; i < n; i++)
        sort_and_uniq(item_sales[i]);

    for(int i = 0; i <= max_day; i++)
        sort_and_uniq(day_sales[i]);

    /*
    for(int i = 0; i < A.size(); i++)
        cout << A[i] << " ";
    cout << "\n";
    cout << s << "\n";
    cout << "\n";
    cout << "\n";
    */

    a = 0; b = 2 * s;
    while(a < b) {
        c = (a + b) / 2;
        vector<ll> B(A);
        vector<int> item_sales_index(n + 1, 0);
        ll bourles = 0;
        for(int d = 1; d <= c; d++) {
            bourles += 1;
            if(d > max_day) continue;
            for(int j = 0; j < day_sales[d].size(); j++) {
                int item = day_sales[d][j];
                if(B[item] == 0) continue;
                if(item_sales_index[item] + 1 == item_sales[item].size() ||
                        item_sales[item][item_sales_index[item] + 1] > c) {
                    int to_spend = min(bourles, B[item]);
                    bourles -= to_spend;
                    B[item] -= to_spend;
                    item_sales_index[item] += 1;
                } else if(item_sales_index[item] < item_sales[item].size()) {
                    item_sales_index[item] += 1;
                }
            }
        }
        /*
        cout << "c = " << c << "\n";
        for(int i = 0; i < B.size(); i++)
            cout << B[i] << " ";
        cout << "bourles " << bourles << "\n";
        cout << "\n";
        */
        if(2 * accumulate(B.begin(), B.end(), 0) <= bourles)
            b = c;
        else
            a = c + 1;
    }
    cout << a << "\n";
    return 0;
}

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m; cin >> n >> m;
    vector<int> need(n + 1);
    for (int i = 1; i <= n; i++)
        cin >> need[i];
    vector<vector<int>> offers(2e5 + 1);
    for (int i = 0; i < m; i++) {
        int x, y; cin >> x >> y;
        offers[x].push_back(y);
    }

    auto check = [&](int days) {
        auto localNeed = need;
        vector<int> last(n + 1);
        for (int day = 1; day <= days; day++)
            for (int type : offers[day])
                last[type] = day;
        int coins = 0;
        for (int day = 1; day <= days; day++) {
            coins++;
            for (int type : offers[day])
                if (last[type] == day) {
                    int val = min(localNeed[type], coins);
                    coins -= val;
                    localNeed[type] -= val;
                }
        }
        return 2 * accumulate(localNeed.begin(), localNeed.end(), 0) <= coins;
    };

    int lo = 0, hi = min(2 * accumulate(need.begin(), need.end(), 0), (int) 2e5) + 1;
    while (hi - lo > 1) {
        int md = (lo + hi) / 2;
        if (check(md))
            hi = md;
        else
            lo = md;
    }
    cout << hi << '\n';
    return 0;
}

//      ——By DD_BOND

//#include<bits/stdc++.h>
#include<functional>
#include<algorithm>
#include<iostream>
#include<sstream>
#include<iomanip>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<cstddef>
#include<cstdio>
#include<memory>
#include<vector>
#include<cctype>
#include<string>
#include<random>
#include<cmath>
#include<queue>
#include<deque>
#include<ctime>
#include<stack>
#include<map>
#include<set>

#define fi first
#define se second
#define MP make_pair
#define pb push_back
#define INF 0x3f3f3f3f
#define pi 3.1415926535898
#define lowbit(a)  (a&(-a))
#define lson l,(l+r)/2,rt<<1
#define rson (l+r)/2+1,r,rt<<1|1
#define Min(a,b,c)  min(a,min(b,c))
#define Max(a,b,c)  max(a,max(b,c))
#define debug(x)  cerr<<#x<<"="<<x<<"\n";

using namespace std;

typedef long long ll;
typedef pair<int,int> P;
typedef pair<ll,ll> Pll;
typedef unsigned long long ull;

const int seed=131;
const ll LLMAX=2e18;
const int MOD=1e9+7;
const double eps=1e-8;
const int MAXN=1e6+10;
const int hmod1=0x48E2DCE7;
const int hmod2=0x60000005;

inline ll sqr(ll x){ return x*x; }
inline int sqr(int x){ return x*x; }
inline double sqr(double x){ return x*x; }
ll gcd(ll a,ll b){ return b==0? a: gcd(b,a%b); }
ll exgcd(ll a,ll b,ll &x,ll &y){ ll d; (b==0? (x=1,y=0,d=a): (d=exgcd(b,a%b,y,x),y-=a/b*x)); return d; }
ll qpow(ll a,ll n){ll sum=1;while(n){if(n&1)sum=sum*a%MOD;a=a*a%MOD;n>>=1;}return sum;}
inline int dcmp(double x){  if(fabs(x)<eps) return 0;   return (x>0? 1: -1); }

map<int,map<int,int>>nx;
int num[MAXN],now[MAXN],event;
vector<int>sale[MAXN],link[MAXN];

bool cmp(int a,int b){
    int num1=nx[event][a],num2=nx[event][b];
    if(num1==num2)  return num[a]>num[b];
    return num1>num2;
}

int main(void)
{
    ios::sync_with_stdio(false);    cin.tie(0);   cout.tie(0);
    // freopen("/My_Mac/Resource/Project__C++/testdata.in","r",stdin);
    //freopen("/My_Mac/Resource/Project__C++/testdata.out","w",stdout);
    int n,m,ans;  cin>>n>>m;
    for(int i=1;i<=n;i++)    cin>>num[i];
    for(int i=1;i<=m;i++){
        int d,t;    cin>>d>>t;
        link[t].pb(d);
    }
    for(int i=1;i<=n;i++){
        link[i].pb(1e6);
        sort(link[i].begin(),link[i].end());
    }
    int l=0,r=1e6;
    while(l<=r){
        int mid=(l+r)>>1,pack=0;
        for(int i=1;i<=n;i++)
            if(link[i].size()){
                int p=lower_bound(link[i].begin(),link[i].begin(),mid)-link[i].begin();
                if(link[i][p]>mid)  p--;
                if(p!=-1){
                    sale[link[i][p]].pb(i);
                }
            }
        for(int i=1;i<=n;i++)   now[i]=num[i];
        for(int i=1;i<=mid;i++){
            pack++;
            for(int j=0;j<(int)sale[i].size();j++)
                while(pack&&now[sale[i][j]]){
                    pack--;
                    now[sale[i][j]]--;
                }
        }
        for(int i=1;i<=n;i++)
            while(now[i]){
                now[i]--;
                pack-=2;
            }
        if(pack<0)  l=mid+1;
        else r=mid-1,ans=mid;
        for(int i=1;i<=200000;i++)  sale[i].clear();
    }
    cout<<ans<<endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=2e5+5;
ll v[N];
ll s[N];
vector<ll> ve[N];
ll n,m,sum;
bool ok(ll x){
	ll now=0;
	ll res=sum;
	for(ll i=1;i<=x;i++){
		now++;
		if(i>n){
			now+=x-i;
			break;
		}
		if(ve[i].size()==0) continue;
		for(auto p:ve[i]){
			if(now>=v[p]) now-=v[p],res-=v[p];
			else res-=now,now=0;
		}
	}
	return now>=res*2;
}
int main(){
	memset(s,-1,sizeof s);
	scanf("%lld %lld",&n,&m);
	for(ll i=1;i<=n;i++){
		scanf("%lld",&v[i]);
		sum+=v[i];
	}
	for(ll i=1;i<=m;i++){
		ll x,y;
		scanf("%lld %lld",&y,&x);
		s[x]=max(s[x],y);
	}
	for(ll i=1;i<=n;i++){
		if(s[i]==-1) continue;
		ve[s[i]].push_back(i);
	}
	ll l=0,r=sum*2;
	ll mid;
	while(l<=r){
		mid=(l+r)>>1;
		if(ok(mid)){
			r=mid-1;
		}else{
			l=mid+1;
		}
	}
	printf("%lld\n",l);
}

#include<bits/stdc++.h>
#define forn(i,n) for(int (i)=0;(i)<(n);(i)++)
#define pt pair<int,int>
#define all(x) (x).begin(),(x).end()
#define INF 1e10
#define vint vector<int>
#define pb push_back
#define mp make_pair
using namespace std;
typedef  long long ll;
int maxn=2*1e5+43;
int n,m;
vint k;
vector<pt> q(maxn);
bool can(ll ans)
{
	vint lst(n,-1);
	for(auto it:q)
	{
		if(it.first<=ans)
		{
			lst[it.second]=max(lst[it.second],it.first);
		}
	}
	vector<vint> off(200001);
	forn(i,n)
	{
		if(lst[i]!=-1)
		off[lst[i]].pb(i);
	}
	int curr=0;
	vint need=k;
	forn(i,ans+1)
	{
		curr++;
		if(i>200000)
		continue;
		for(auto it:off[i])
		{
			if(need[it]<=curr)
			{
				curr-=need[it];
				need[it]=0;
			}
			else
			{
				need[it]-=curr;
				curr=0;
				break;
			}
		}
	}
	return (2*accumulate(need.begin(),need.end(),0)<=curr);
}
int main()
{
	scanf("%d%d",&n,&m);
	k=vint(n);
	forn(i,n)
	scanf("%d",&k[i]);
	forn(i,m)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		a--;
		b--;
		q[i].first=a;
		q[i].second=b;
	}
	//ll uplimit=2*accumulate(k.begin(),k.end(),0);
	ll l=0;
	ll r=400000;
	while(true)
	{
		if(r==l)
		{
			cout<<r+1<<endl;
			return 0;
		}
		ll mid=(r+l)/2;
		if(can(mid))
		r=mid;
		else
		l=mid+1;
	}
	while (r - l > 1) {
		int mid = (l + r) >> 1;
		if (can(mid)) r = mid;
		else l = mid;
	}

	for (int i = l; i <= r; ++i) {
		if (can(i)) {
			cout << i + 1 << endl;
			return 0;
		}
	}
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forn(i, n) for (ll i = 0; i < (n); i++)
#define fori(i, b, e) for (ll i = (b); i < (e); i++)
#define forr(i, b, e) for (ll i = (b); i >= (e); i--)
#define allele(v) v.begin(), v.end()
#define fi first
#define se second

int n, m;
vector<int> k;
vector<pair<int, int>> s;
bool check(int days)
{
	// cout << days << ':';
	vector<int> rmn(k);
	vector<int> o(n);
	forn(i, m)
	{
		if(s[m].fi <= days) o[s[m].se] = max(o[s[m].se], s[m].fi);
	}
	int b = 0;
	fori(day, 1, days + 1)
	{
		b++;
		forn(t, n)
		{
			if(o[t] == day)
			{
				int am = min(rmn[t], b);
				// cout << day << ' ' << am << ' ' << t << ' ';
				b -= am, rmn[t] -= am;
			}
		}
	}
	int rmd = 0;
	forn(i, n) rmd += rmn[i];
	// cout << b << ' ' << rmd << endl;
	return (b >= rmd * 2);
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n >> m;
	k = vector<int>(n);
	s = vector<pair<int, int>>(m);
	forn(i, n) cin >> k[i];
	forn(i, m) cin >> s[i].fi >> s[i].se;

	int sum = 0;
	forn(i, n) sum += k[i];
	int l = 1, r = sum * 2;
	while(1)
	{
		if(l == r) return cout << l, 0;
		int mid = (l + r) / 2;
		bool res = check(mid);
		if(res) r = mid;
		else l = mid + 1;
	}
	return 0;
}

/*
digu_J - Digvijay Janartha
NIT Hamirpur - INDIA
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

template < typename T > using ordered_set = tree < T, null_type, less < T >, rb_tree_tag, tree_order_statistics_node_update >;
template < typename T > using MinPriorityQueue = priority_queue < T, vector < T >, greater < T > >;

#ifndef ONLINE_JUDGE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template < typename Arg1 >
void __f(const char* name, Arg1&& arg1) {
    cout << name << " : " << arg1 << std :: endl;
}
template < typename Arg1, typename... Args >
void __f(const char* names, Arg1&& arg1, Args&&... args) {
    const char* comma = strchr(names + 1, ',');
    int len = comma - names;
    for (int i = 0; i < len; ++i) {
        cout << names[i];
    }
    cout <<  " : " << arg1 << " | ";
    __f(comma + 1, args...);
}
#else
#define trace(...)
#endif

typedef double db;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair < ll, ll > pll;
typedef pair < int, int > pii;
typedef vector < ll > vll;
typedef vector < int > vi;

#define eb emplace_back
#define pb push_back
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define unique_sort(x) (sort(x.begin(), x.end()), x.resize(distance(x.begin(), unique(x.begin(), x.end()))))
#define fast_io() ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0)

const ll LINF = LLONG_MAX, base = 1e9, MOD = 1e9 + 7, N = 2e5 + 5, M = 1e6 + 5;
const int INF = INT_MAX;
const db PI = acos(-1);

int n, m, mx, a[N], b[N];
pii p[N];

void test();
bool check(int x);

int main() {
    fast_io();
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    test();
    #ifndef ONLINE_JUDGE
        cout << "Time: " << (int)(clock() * 1000. / CLOCKS_PER_SEC) << "ms";
    #endif
    return 0;
}

void test() {
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
        mx += a[i];
    }
    for (int i = 0; i < m; ++i) {
        cin >> p[i].F >> p[i].S;
    }
    sort(p, p + m);
    int lo = 0, hi = 2 * mx, ans = 2 * mx, mid;
    while (lo <= hi) {
        mid = lo + (hi - lo) / 2;
        if (check(mid)) {
            ans = mid, hi = mid - 1;
        } else {
            lo = mid + 1;
        }
    }
    cout << ans << "\n";
}

bool check(int x) {
    for (int i = 1; i <= n; ++i) {
        b[i] = a[i];
    }
    int ans = 0, cur = 0;
    bool ok = true;
    for (int i = 0; i < m; ++i) {
        if (p[i].S > x) {
            cur += x - p[i - 1].F;
            ok = false;
            break;
        }
        if (!i) {
            cur = p[i].F;
        } else {
            cur += p[i].F - p[i - 1].F;
        }
        int temp = cur;
        if (b[p[i].S] and cur) {
            if (b[p[i].S] - cur > 0) {
                b[p[i].S] = b[p[i].S] - cur, cur = 0;
            } else {
                cur -= b[p[i].S];
                b[p[i].S] = 0;
            }
        }
        ans += temp - cur;
    }
    if (ok) {
        cur += x - p[m - 1].F;
    }
    ans += cur / 2;
    return (ans >= mx ? true : false);
}

#include <bits/stdc++.h>

using namespace std;

#define int long long

typedef pair<int,int> ii;
ii q[200001];
int n,m;
int a[200001];
int b[200001];
int lst[200001];
vector<int> z[500001];

bool check(int day)
{
	memset(lst,0,sizeof lst);
	for (int i=1;i<=n;i++)
		b[i] = a[i];
	for (int i=1;i<=m;i++)
		if (q[i].first <= day)
			lst[q[i].second] = max(lst[q[i].second],q[i].first);
	for (int i=1;i<=n;i++)
		if (lst[i] != 0)
			z[lst[i]].push_back(i);
	int cur = 0;
	for (int i=1;i<=day;i++)
	{
		cur++;
		for (int j=0;j<z[i].size();j++)
		{
			int used = min(cur,b[z[i][j]]);
			cur -= used;
			b[z[i][j]] -= used;
		}
		z[i].clear();
	}
	int zz = 0;
	for (int i=1;i<=n;i++)
		zz += b[i];
	return (zz*2 <= cur);
}

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

	cin >> n >> m;
	for (int i=1;i<=n;i++)
		cin >> a[i];
	for (int i=1;i<=m;i++)
		cin >> q[i].first >> q[i].second;
	int l = 0, r = 400000;
	int res;
	while (l < r)
	{
		int mi = (l+r)/2;
		if (check(mi))
		{
			res = mi;
			r = mi-1;
		}
		else
			l = mi+1;
	}
	cout << res;
}

#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

#define dos pair<int, int>
#define day first
#define item second

int n, m;
int data[200002];
int temp[200002];
int dataDay[200002];
dos sales[200002];

bool solve(int lastDay) {
    for (int i = 0; i < n; i++) {
        temp[i] = data[i];
    }
    memset(dataDay, -1, sizeof(dataDay));

    for (int i = m - 1; i >= 0; i--) {
        if (sales[i].day <= lastDay && dataDay[sales[i].item] == -1) {
            dataDay[sales[i].item] = i;
        }
    }

    int money = 1;
    int day = 1;
    for (int i = 0; i < m; i++) {
        if (sales[i].day > lastDay) {
            money += lastDay - day;
            day = lastDay;
            break;
        }
        money += sales[i].day - day;
        day = sales[i].day;
        //printf("> %d %d\n", day, money);

        if (dataDay[sales[i].item] == i) {
            int b = min(money, temp[sales[i].item]);
            money -= b;
            temp[sales[i].item] -= b;
        }
    }
    if (day < lastDay) {
        money += lastDay - day;
    }
    //printf("$ pre %d\n", money);
    for (int i = 0; i < n; i++) {
        int b = 2 * temp[i];
        money -= b;
    }
    //printf("$ post %d\n", money);
    return (money >= 0);
}

int main() {
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; i++) {
        scanf("%d", &data[i]);
    }
    for (int i = 0; i < m; i++) {
        scanf("%d %d", &sales[i].day, &sales[i].item);
        sales[i].item--;
    }

    sort(sales, sales + m);

    int a = 0;
    int b = 2 * 100000 * 2;
    int c;
    while (b - a > 1) {
        c = (a + b) / 2;
        // printf("%d %d %d\n", a, b, c);
        if (solve(c)) {
            b = c;
        } else {
            a = c;
        }
    }

    printf("%d\n", c);
}

#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;

int n, m, t, d, l, r = 0, cow[1017], sum = 0, j = 0;

vector<int> v[1017];

struct node
{
	int d;
	int id;
}a[1017];

bool cmp(node a, node b)
{
	return a.d < b.d;
}

int ok(int x)
{
	int mon = 0, less = 0;
	sort(a, a+j, cmp);
	for(int i = 0; i < j && a[i].d <= x; i++)
	{
		if(i != 0)
		mon += a[i].d-a[i-1].d;
		else mon = a[i].d;
		if(mon >= cow[a[i].id])
		{
			mon -= cow[a[i].id];
			less += cow[a[i].id];
		}
		else
		{
			less += mon;
			mon = 0;
		}
	}
	if(2*sum-less <= x) return 1;
	else return 0;
}

int main()
{
	cin>>n>>m;
	for(int i = 1; i <= n; i++)
	{
		cin>>cow[i];
		r += 2*cow[i];
		sum += cow[i];
	}
	while(m--)
	{
		cin>>d>>t;
		v[t].push_back(d);
	}
	for(int i = 1; i <= n; i++)
	sort(v[i].begin(), v[i].end());
	for(int i = 1; i <= n; i++)
	{
		if(!v[i].size()) continue;
		a[j].d = v[i][v[i].size()-1];
		a[j++].id = i;
	}
	l = -1;
	while(l+1 < r)
	{
		int mid = (l+r)/2;
		if(ok(mid)) r = mid;
		else l = mid;
	}
	cout<<r<<endl;
	return 0;
}

#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>

using namespace std;

bool Jo(vector<int> &v, vector<pair<int, int>> &sale, int n, int m, int k)
{
    vector<int> minusSale(n, 0);
    int foglal = 0, sum = 0;

    for(int i = 0; i < m; i++)
    {
        if(sale[i].first > k)
            break;
        int x = min(sale[i].first - foglal, v[sale[i].second-1] - minusSale[sale[i].second-1]);
        minusSale[sale[i].second-1] += x;
        foglal += x;
        sum += x;
    }

    for(int i = 0; i < n; i++)
        sum += (v[i] - minusSale[i])*2;

    if(sum <= k)
        return true;
    return false;
}

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

    int n, m;
    cin>>n>>m;

    vector<int> v(n);
    vector<pair<int, int>> sale(m);

    for(int i = 0; i < n; i++)
        cin>>v[i];

    for(int i = 0; i < m; i++)
        cin>>sale[i].first>>sale[i].second;

    sort(sale.begin(), sale.end());

    int s = -1, e = 400000;

    while(s+1 < e)
    {
        int mid = (s+e+1)/2;

        if(Jo(v, sale, n, m, mid))
            e = mid;
        else
            s = mid;
    }

    cout<<e<<"\n";

    return 0;
}

#include <bits/stdc++.h>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <iomanip>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//setbase - cout << setbase (16); cout << 100 << endl; Prints 64
//setfill -   cout << setfill ('x') << setw (5); cout << 77 << endl; prints xxx77
//setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx
//cout.precision(x)  cout<<fixed<<val;  // prints x digits after decimal in val

using namespace std;
using namespace __gnu_pbds;
 	// find_by_order()  // order_of_key
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
#define f(i,a,b) for(ll i=a;i<b;i++)
#define rep(i,n) f(i,0,n)
#define fd(i,a,b) for(ll i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define inff (1000*1000*1000+5)
#define all(a) a.begin(),a.end()
#define tri pair<int,pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define pqueue priority_queue< int >
#define pdqueue priority_queue< int,vi ,greater< int > >
#define flush fflush(stdout)
#define primeDEN 727999983
#define SPEED ios_base::sync_with_stdio(false) ;cin.tie(NULL) ;cout.tie(NULL) ;
#define fp(i,a,n) for(ll i=n-1; i>a ;i--)
#define deb(x) cout << #x << " ---> " << x << endl;
#define X first
#define Y second
#define pia 3.1415926536
#define mod 1000000007
#define N 100050
#define ml map<ll,ll>
#define mll map<pll,ll>
#define vvl vector<vl>
#define letsh(a,b) a<<b
#define rigsh(a,b) a>>b
mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()) ;
		ll lcm(ll a, ll b){
	       return a / __gcd(a, b) * b;
	    }
	   bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}

          ll power(ll a,ll n)
	   {
        ll ans=1;
        while(n)
		{
        if(n&1) ans=(ans*a)%mod;
        a=(a*a)%mod ;
        n=n>>1;
   		 }
   		 return ans;
      }
      ll power2(ll a,ll n)
      {
      	ll ans =1 ;
      	while(n)
      	{
      		if(n&1) ans =(ans*a) ;
      		a = (a*a) ;
      		n =n>>1 ;
		  }
		  return ans ;
	  }
	  vvl dir({{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) ;

	  void solve()
	  {
	    ll n ,m ;cin>>n>>m ;ll sum =0 ;
	    vl k(n) ;f(i,0,n) cin>>k[i] ,sum +=k[i];
		map<ll,set<ll> > p ;
		vll a(m) ;f(i,0,m) cin>>a[i].X>>a[i].Y ,p[a[i].Y].insert(a[i].X) ;
	    sort(all(a)) ;
	    ll lf =0,rg = 2*sum ;
	    while(rg -lf >1)
	    {
	    	ll mid =(rg+lf)/2 ;
	        ll dif = sum ;
			ll mon =0 ;
            ll ls =0 ;
			f(i,0,a.size())
			{
				if(a[i].X >mid) break ;
				mon +=(a[i].X-ls) ;ll curelement = a[i].Y ;
			  auto it = p[curelement].upper_bound(a[i].X) ;
			  if(it == p[curelement].end() || *it >mid)
			  {
			  	dif -=min(mon,k[curelement-1]) ;
			  	mon -= min(mon,k[curelement-1]) ;
			   }
			   ls = a[i].X ;
			}

			mon +=(mid -ls) ;
		//	cout<<mon<<" "<<dif<<" "<<ls<<endl ;
			if(mon >= 2*dif) rg= mid ;
			else lf = mid ;
		//	cout<<lf<<" "<<rg<<endl ;
		}
		cout<<rg<<endl ;
	  }
	  int main()
	  	{
	  	    SPEED
	  	    ll t =1 ;
	         while(t--) solve() ;
		}

/*
    Mbak Rose Dong
*/
#include<bits/stdc++.h>
using namespace std;
int need[200200];
map<int,int> mp;
set<int> s[200200];
int jennie, rose;
int calc(int now)
{
    int sum = 0;
    vector<pair<int,int> > vi;
    for(auto x : mp)
    {
        if(s[x.first].empty()) continue;
        auto it = s[x.first].lower_bound(now);
        it--;
        int day = *it;
        if(day > now) continue;
        vi.push_back(make_pair(day,x.second));
    }
    sort(vi.begin(), vi.end());
    for(auto x : vi)
    {
        int temp = min(x.first-sum, x.second);
        sum += min(now, temp);
        now -= min(now,temp);
    }
    return (now - (jennie-sum)*2);
}
int main()
{
    int n,i,j,k,m,x,y,ans,curr,res,now;
    scanf("%d %d",&n,&m);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&need[i]);
        jennie += need[i];
        if(need[i] > 0)
        {
            mp[i] = need[i];
        }
    }
    for(i=1;i<=m;i++)
    {
        scanf("%d %d",&x,&y);
        s[y].insert(x);
    }
    int low,mid,high;
    low = 1;
    high = 400000;
    mid = (low+high)/2;
    while(low <= high)
    {
        if(calc(mid) >= 0)
        {
            rose = mid;
            high = mid-1;
        }
        else
        {
            low = mid+1;
        }
        mid = (low+high)/2;
    }
    printf("%d\n",rose);
    return 0;
}

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// order_of_key (val): returns the no. of values less than val
// find_by_order (k): returns the kth largest element.(0-based)

#define ll int
#define ld long double
#define ff first
#define ss second
#define pb push_back
#define pi pair<ll,ll>
#define md (ll)(1e9+7)
#define all(X) X.begin(),X.end()

// for pair comparison function(ascending order) use return (i1.ff < i2.ff);

/* string operations :
   str.substr (x,y) : returns a substring str[x],str[x+1],...str[x+y-1]
   str.substr (x) : returns a substring str[x],... end of string
   str.find(qtr) : returns the first occurenece of qtr in str */

const int M=1e6+6;

ll pwr(ll a,ll n,ll m)
{
	ll p=1;
	while(n>0)
	{
		if(n%2==1)
			p=(p*a)%m;
		a=(a*a)%m;
		n=n/2;
	}
	return p;
}

ll ar[M],br[M],mrk[M],n,ans[M],gf,cf;
vector<ll> adj[M];
queue<ll> pq;

bool check(ll d)
{
	if(ans[d] > 0)
	{
		if(ans[d] == 2)
			return 0;
		else
			return 1;
	}

	ll i,c=0,sm=0;

	for(i=1;i<=n;++i)
	{
		ar[i] = br[i];
		sm += ar[i];
		mrk[i] = 0;
	}

	for(i=d;i>=1;i--)
	{
		for(auto v:adj[i])
		{
			if(mrk[v] == 0)
			{
				pq.push(v);
				mrk[v] = 1;
			}
		}
		if(pq.empty())
		{
			c++;
			continue;
		}
		ll u = pq.front();
		while(ar[u] == 0)
		{
			pq.pop();
			if(pq.empty())
				break;
			u = pq.front();
		}
		if(pq.empty())
		{
			c++;
			continue;
		}
		ar[u]--;
		sm--;
	}

	gf = sm;
	cf = c;

	while(!(pq.empty()))
		pq.pop();

	if(c>=2*sm)
	{
		ans[d] = 1;
		return 1;
	}
	else
	{
		ans[d] = 2;
		return 0;
	}

}

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

	ll m,i,l,r,mid,d,t;

	cin >> n >> m;

	for(i=1;i<=n;++i)
		cin >> br[i];

	for(i=1;i<=m;++i)
	{
		cin >> d >> t;
		adj[d].pb(t);
	}

	l = 1;
	r = 2e5;

	while(l<=r)
	{
		mid = l + (r-l)/2;
		if(check(mid) == 1 && (mid == 1 || check(mid-1)==0))
			break;
		else if(check(mid) == 1 && check(mid-1) == 1)
			r = mid-1;
		else if(check(mid) == 0)
			l = mid+1;
	}

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

#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 200010;
const int eps =1e-5;
typedef long long ll;
struct node
{
	ll day,t;
}vis[maxn],las[maxn];
ll last[maxn],num[maxn];
bool cmp(node & a , node & b){return a.day < b.day;}
ll n,m,sum = 0;

bool judge(ll x,ll y){
	memset(last,0,sizeof(last));
	ll i = 0;
	while(vis[i].day <= x){
		last[vis[i].t] = vis[i].day;
		i++;
		if(i == m) break;
	}
	int cnt = 0;
	for(int j = 1 ; j <= n ;j++){
		if(last[j] != 0){
			las[cnt].day = last[j];
			las[cnt].t = j;
			cnt++;
		}
	}
	ll money = 0;
	sort(las,las + cnt,cmp);
	for(int j = 0 ; j < cnt ; j++){
		if(j == 0 ) money += las[j].day;
		else money += las[j].day - las[j - 1].day;
		if(money >= num[las[j].t]){
			money -= num[las[j].t];
			y -= num[las[j].t];
		}else{
			y -= money;
			money = 0;
		}
	}
	money += x - las[cnt - 1].day;
	if(money >= y*2){
		return true;
	}else{
		return false;
	}
}
int main(){
	scanf("%lld %lld",&n,&m);
	for(int i = 1 ; i <= n ;i++){
		scanf("%lld",&num[i]);
		sum += num[i];
	}
	for(int i = 1 ; i <= m ; i++){
		scanf("%lld %lld",&vis[i].day,&vis[i].t);
	}
	sort(vis,vis + m,cmp);
	int l = 1,r = 2*sum;
	while(r - l > eps){
		int mid = (l + r)/2;
		if(judge(mid,sum)){
			r = mid;
		}else{
			l = mid + 1;
		}
	}
	printf("%d\n",l);
	// for(int i = 1 ; i <= sum*2 ; i++){
	// 	if(judge(i,sum)){
	// 		printf("%d\n",i);
	// 		break;
	// 	}
	// }
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define all(v) ((v).begin()),((v).end())
#define ll long long
#define fastIO cout << fixed << setprecision(12), ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
double const EPS = 1e-12, PI = acos(-1);
const int N = 2e5 + 9, M = 1e7 + 9, OO = 1e9 + 7, MOD = 1e9 + 7, MOD2 = 998244353;
const ll inf = 1e18;

int need[2*N], cnt[2*N], temp[2*N];
int n, m;
set<int> st[2*N];
vector<int> vec[2*N];

int can(int mid) {
	int total = 0, taken = 0;
	for (int i = 1; i <= n; ++i)
		temp[i] = need[i];
	int ptr = 1;
	while(ptr <= mid) {
		++total;
		for(auto it: vec[ptr]) {
			while(total && temp[it]) {
				--total;
				--temp[it];
				++taken;
			}
		}
		++ptr;
	}
	taken += total / 2;
	return taken;
}

int main() {
	fastIO;
#ifdef LOCAL
//	freopen("input.in", "rt", stdin);
#endif
	int d, t, left = 0;
	cin >> n >> m;
	for (int i = 1; i <= n; ++i)
		cin >> need[i], left += need[i];
	for (int i = 0; i < m; ++i) {
		cin >> d >> t;
		st[d].insert(t);
	}
	for (int i = N; i > 0; --i)
		for(auto it: st[i])
			vec[i].push_back(it);
	int start = 0, end = left * 2, mid, ans = left * 2;
	while(start <= end) {
		mid = start + (end - start) / 2;
		int val = can(mid);
		if(val >= left) {
			ans = mid;
			end = mid - 1;
		} else {
			start = mid + 1;
		}
	}
	cout << ans;
	return 0;
}

/* Author : bhavye9499 - Bhavye Anand Gupta */

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

typedef long long ll;
typedef long double ld;

#define endl "\n"
#define pb emplace_back
#define fi first
#define se second
#define mp make_pair
#define pii pair<ll,ll>
#define max_heap priority_queue<ll>
#define min_heap priority_queue<ll, vector<ll>, greater<ll> >
#define showArr(A,a,n) {for(int i = a; i < a + n; i++) cout << A[i] << " "; cout << endl;}
#define showPair(A,a,n) {for(int i = a; i < a + n; i++) cout << A[i].fi << " " << A[i].se << endl;}

const ll MOD = 1e9 + 7;
const ll MAX = 2e5 + 5;
ll n, m;
ll A[MAX];
vector<pii> B;

bool fun(ll aday) {
	ll last[n];
	memset(last, -1, sizeof(n));
	for(int i = 0; i < m && B[i].fi < aday; i++) {
		last[B[i].se] = B[i].fi;
	}
	vector<ll> ldtypes[MAX];
	for(int i = 0; i < n; i++) {
		if(last[i] != -1) {
			ldtypes[last[i]].pb(i);
		}
	}
	ll req[n];
	for(int i = 0; i < n; i++) {
		req[i] = A[i];
	}
	ll money = 0;
	for(int i = 0; i < aday; i++) {
		money++;
		for(ll x : ldtypes[i]) {
			if(req[x] <= money) {
				money -= req[x];
				req[x] = 0;
			}
			else {
				req[x] -= money;
				money = 0;
				break;
			}
		}
	}
	ll left = accumulate(req, req + n, 0);
	return (2 * left <= money);
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	B.clear();

	cin >> n >> m;
	for(int i = 0; i < n; i++) {
		cin >> A[i];
	}
	for(int i = 0; i < m; i++) {
		ll x, y;
		cin >> x >> y;
		x--; y--;
		B.pb(mp(x, y));
	}

	sort(B.begin(), B.end());
	ll low = 1, high = 2 * accumulate(A, A + n, 0);
	while(high - low > 1) {
		ll mid = (high + low) / 2;
		if(fun(mid)) {
			high = mid;
		}
		else {
			low = mid;
		}
	}

	cout << ((fun(low)) ? low : high) << endl;

}

/*input
5 6
1 2 0 2 0
2 4
3 3
1 5
1 2
1 5
2 3

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

#ifdef TEMPLATE
typedef long long ll;
typedef long double ld;
typedef complex<ld> cd;

typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef pair<ld, ld> pd;

typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ld> vd;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef vector<pi> vpi;
typedef vector<vpi> vpii;
typedef vector<pl> vpl;
typedef vector<cd> vcd;
typedef vector<pd> vpd;
typedef vector<bool> vb;
typedef vector<vb> vbb;
typedef std::string str;
typedef std::vector<str> vs;

#define x first
#define y second
#define debug(...) cout<<"["<<#__VA_ARGS__<<": "<<__VA_ARGS__<<"]\n"

const int MOD = 1000000007;
const ll INF = std::numeric_limits<ll>::max();
const int MX = 400101;
const ld PI = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270L;

template<typename T>
pair<T, T> operator+(const pair<T, T> &a, const pair<T, T> &b) { return pair<T, T>(a.x + b.x, a.y + b.y); }
template<typename T>
pair<T, T> operator-(const pair<T, T> &a, const pair<T, T> &b) { return pair<T, T>(a.x - b.x, a.y - b.y); }
template<typename T>
T operator*(const pair<T, T> &a, const pair<T, T> &b) { return (a.x * b.x + a.y * b.y); }
template<typename T>
T operator^(const pair<T, T> &a, const pair<T, T> &b) { return (a.x * b.y - a.y * b.x); }
#endif

void baik(int a) {
	printf("%d\n", a);
	exit(0);
}

vi reik;

bool comp(const int &a, const int &b){
	return reik[a] > reik[b];
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int N, M;
	cin >> N >> M;
	reik = vi(N + 1);
	int nenul = 0;
	int sum = 0;
	for (int i = 1; i <= N; ++i) {
		cin >> reik[i];
		nenul += bool(reik[i]);
		sum += reik[i];
	}

	vi nuol[MX];
	int a, b;
	for (int i = 0; i < M; ++i)
	{
		cin >> a >> b;
		nuol[a].push_back(b);
	}

	int turiu = 0;
	for (int i = 1; nenul; ++i)
	{
		turiu++;
		sort(nuol[i].begin(), nuol[i].end(), comp);

		for (auto u: nuol[i])
		{
			int minus = min(reik[u], turiu);
			reik[u] -= minus;
			if (minus and !reik[u]) nenul--;
			sum -= minus;
			turiu -= minus;
		}

		if (turiu >= sum * 2)
			baik(i);
	}
}

/* Look for:
* special cases (n=1?)
* overflow (ll vs int?)
* the exact constraints (multiple sets are too slow for n=10^6 :( )
* array bounds
*/

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

template <class T>
inline bool uin(T& a, T b) { return a > b ? (a = b, true) : false; }
template <class T>
inline bool uax(T& a, T b) { return a < b ? (a = b, true) : false; }

const int nax = 2e5 + 10;

vector<int> offer[nax];
int K[nax];
int N, M;

bool can(int m) {
	vector<int> last(N, -1);
	for (int i = 0; i <= min(m, nax - 1); ++i)
		for (int x : offer[i]) last[x] = i;
	vector<vector<int>> temp_offer(nax);
	for (int i = 0; i < N; ++i) {
		if (last[i] == -1) continue;
		temp_offer[last[i]].push_back(i);
	}
	int need[nax];
	memcpy(need, K, sizeof(K));
	int cur_money = 1;
	for (int i = 0; i <= m; ++i, ++cur_money) {
		if (i > 2e5) continue;
		for (int x : temp_offer[i]) {
			if (cur_money >= need[x]) {
				cur_money -= need[x];
				need[x] = 0;
			} else {
				need[x] -= cur_money;
				cur_money = 0;
				break;
			}
		}
	}
	return accumulate(need, need + nax, 0) * 2 <= cur_money;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> N >> M;
	for (int i = 0; i < N; ++i) cin >> K[i];
	for (int d, t, i = 0; i < M; ++i) {
		cin >> d >> t;
		--d, --t;
		offer[d].push_back(t);
	}
	int l = 0, r = 4e5 + 10;
	while (r - l > 1) {
		int m = (l + r) / 2;
		if (can(m))
			r = m;
		else
			l = m;
	}
	for (int i = l; i <= r; ++i) {
		if (can(i)) {
			cout << i + 1 << '\n';
			break;
		}
	}
}

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 400000;

int n, m, ans, sum;
int a[maxn + 10];
vector<int> s[maxn + 10];
bool used[maxn + 10];

void print(int a[], int n, int st = 0) {
    for (int i = 0; i < n; i++) {
        if (i != 0) printf(" ");
        printf("%d", a[i + st]);
    }
    printf("\n");
}
void init() {
    scanf("%d%d", &n, &m);
    sum = 0;
    for (int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        sum += a[i];
    }
    for (int i = 0; i <= maxn; i++) s[i].clear();
    for (int i = 0; i < m; i++) {
        int x, y;
        scanf("%d%d", &x, &y);
        s[x].push_back(y);
    }
}
bool check(int day) {
    if (day >= sum * 2) return true;
    for (int i = 1; i <= n; i++) used[i] = false;
    int top = -1, cur = 0;
    for (int i = day; i >= 1; i--) {
        int mx = 0;
        for (int j = 0; j < s[i].size(); j++) {
            int x = s[i][j];
            if (a[x] > 0 /* && !used[x]*/) {
                used[x] = true;
                mx = min(mx + a[x], i);
            }
        }
        if (mx > 0) {
            if (top == -1) {
                cur = mx;
                top = i - mx;
            }
            else {
                mx = min(mx, top);
                cur += mx;
                top = min(top, i - mx);
            }
        }
    }
    return (sum * 2 - cur <= day);
}
void doit() {
    int left = 1, right = maxn, mid, ans;
    while (left <= right) {
        mid = (left + right) >> 1;
        if (check(mid)) {
            right = mid - 1;
            ans = mid;
        }
        else {
            left = mid + 1;
        }
    }
    printf("%d\n", ans);
}
int main()
{
    //freopen("test.in", "r", stdin);
        init();
        doit();
    return 0;
}

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

#define int long long

using namespace std;
int INF = 2 * 100000 + 1;
int n, m, all;
vector<int> products;
vector<pair<int, int>> sales;
bool check_day (int TODAY);

signed main()
{
    cin >> n >> m;
    products.resize(n);
    sales.resize(m);
    for (int i = 0; i < n; ++i) {
        cin >> products[i];
        all += products[i];
    }
    INF = all * 2;
    for (int i = 0; i < m; ++i) {
        int day, type; cin >> day >> type;
        --type;
        sales[i] = make_pair(day, type);
    }
    int TODAY = 1, l = 1, r = INF;
    while ((l + 1) < r) {
        TODAY = (r + l) / 2;
        if (check_day(TODAY)) {
            r = TODAY;
        } else {
            l = TODAY;
        }
    }
    cout << r;
    return 0;
}

bool check_day (int TODAY)
{
    bool ok = false;
    int MONEY = 0;
    vector<int> last_days_of_sales(n, 0); // last[i] - last day (<= TODAY) of sale for product i-type
    for (pair<int, int> temp : sales) {
        if (temp.first <= TODAY && temp.first > last_days_of_sales[temp.second]) {
            last_days_of_sales[temp.second] = temp.first;
        }
    }
    vector<vector<int>> days(TODAY + 1); // days[i] - list of types of products with last day of sale i
    for (int i = 0; i < n; ++i) {
        if (last_days_of_sales[i]) {
            days[last_days_of_sales[i]].push_back(i);
        }
    }
    vector<int> copy_products = products;
    for (int day = 1; day <= TODAY; ++day) {
        ++MONEY;
        for (int j = 0; j < days[day].size(); ++j) {
            int type = days[day][j];
            if (MONEY >= copy_products[type]) {
                MONEY -= copy_products[type];
                copy_products[type] = 0;
            } else {
                copy_products[type] -= MONEY;
                MONEY = 0;
                break;
            }
        }
    }
    int sum = 0;
    for (int i : copy_products) {
        sum += i;
    }
    if (sum * 2 <= MONEY) {
        ok = true;
        //cerr << MONEY << '\n';
    }
    return ok;
}

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

struct node
{
    int d,t;
}a[200005];
bool cmp(node a,node b)
{
    return a.d<b.d;
}
int k[200005],kx[200005];
int main()
{
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int n,m;cin>>n>>m;
    int tot = 0;
    rep(i,n) cin>>k[i],tot+=k[i];
    rep(i,n) cout<<k[i]<<" ";cout<<endl;
    rep(i,m) cin>>a[i].d>>a[i].t;
    sort(a+1,a+1+m,cmp);
    int lo = tot, hi = 2*tot;
    while(lo<hi)
    {
        int mid=(lo+hi)/2;
        memcpy(kx, k, sizeof(int)*(n+1));
        int cnt = 0, mn = mid;
        for(int i=m;i>=1;--i)
        {
            if(a[i].d>mid) continue;
            mn = min(mn, a[i].d);
            while(kx[a[i].t]&&mn) kx[a[i].t]--,mn--,cnt++;
        }
        if(cnt>=2*tot-mid) hi=mid;
        else lo=mid+1;
    }
    cout<<lo<<endl;
}

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
ll blur;
ll k[1005], kk[1005];
vector<int> sale_d[2005];
set<int> sale_t[2005];
bool check(int day){
    if (day < 0) return false;
    blur = 0;
    for (int i=1;i<=n;i++){
        kk[i] = k[i];
    }
    vector<int> sale_back;
    for (int d=1;d<=day;d++){
        blur++;
        // check sale
        sale_back.clear();
        for (int i=0;i<sale_d[d].size();i++){
            int type = sale_d[d][i];
            if ( *(sale_t[type].upper_bound(d)) <= day ) {
                sale_back.push_back(type);
                continue;
            }
            int x = min(blur, kk[type]);
            blur -= x;
            kk[type] -= x;
        }
        for (int i=0;i<sale_back.size();i++){
            int type = sale_back[i];
            int x = min(blur, kk[type]);
            blur -= x;
            kk[type] -= x;
        }
    }
    ll cnt = 0;
    for (int i=1;i<=n;i++){
        cnt += kk[i];
    }
    if (blur>=cnt*2) return true;
    else return false;
}
int bs(int day){
    if (check(day)){
        if (check(day-1)){
            return 1; // too large
        }else{
            return 0; // found
        }
    }else{
        return -1; // too small
    }

}

int main(void){
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        cin >> k[i];
    }
    for (int i=0;i<m;i++){
        int d,t;
        cin >> d >> t;
        sale_d[d].push_back(t);
        sale_t[t].insert(t);
    }
    int u = 0, v = 2005, cur = -1;
    while(u<v){
        cur = (u+v)/2;
        int res = bs(cur);
        if (res == 0){
            break;
        }else if (res == -1){
            u = cur+1;
        }else{
            v = cur;
        }
    }
    assert(cur!=-1);
    cout << cur << endl;
}

#include <bits/stdc++.h>

using namespace std;

int64_t inf = 1000 * 1000 * 1000;
int64_t inf64 = inf * inf;
int64_t nll = 0;

#define ll long long
#define se second
#define fi first
#define endl '\n'
#define eb emplace_back

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int64_t n, m, sum = 0;
    cin >> n >> m;
    vector <int64_t> a(1005);
    vector <pair<int64_t, int64_t>> b;
    for (int32_t i = 0; i < n; ++i)
    {
        cin >> a[i + 1];
        sum += a[i + 1];
    }
    for (int32_t i = 0; i < m; ++i)
    {
        int64_t x, y;
        cin >> x >> y;
        b.eb(x, y);
    }
    sort(b.begin(), b.end());
    int64_t l = -1, r = 2005;
    vector <int64_t> tmp = a;
    int64_t k = 0;
    while (k < 2005)
    {
        //cout << "---------\n";
        //k = (l + r) / 2;
        int32_t cnt = 0;
        int32_t bal = 0;
        for (int32_t i = 0; i < m; ++i)
        {
            bal = b[i].fi - cnt;
            if (b[i].fi <= k)
            {
                while (tmp[b[i].se] > 0)
                {
                    if (bal > 0)
                    {
                        ++cnt;
                        --tmp[b[i].se];
                        --bal;
                        //cout << b[i].fi << " " << b[i].se << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        //cout << "k: " << k << " - ";
        if ((sum - cnt) * 2 + cnt <= k)
        {
            cout << k;
            break;
            r = k;
            //cout << "good";
        }
        else
        {
            l = k;
            //cout << "bad";
        }
        //cout << endl;
            ++k;
        tmp = a;
    }
    //cout << r;
}
/*

*/

#include <bits/stdc++.h>
using namespace std;
template<class T> ostream& operator<<(ostream &os, vector<T> V) {
os << "[ "; for(auto v : V) os << v << " "; return os << "]";}
template<class L, class R> ostream& operator<<(ostream &os, pair<L,R> P) {
    return os << "(" << P.first << "," << P.second << ")";}

// #define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cout << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...) 1
#endif
typedef long long ll;
typedef double ld;
#define pll pair<ll,ll>
#define pb push_back
#define mp(x, y) make_pair((x), (y))
#define F first
#define S second
#define I insert
#define vll vector<ll>
#define vpll vector<pll>
#define all(x) (x).begin(), (x).end()
#define sz(x) (ll)(x).size()

int n , m , c , d , t , Total;

int req[200007];

map<int , vector<int> > sale;

bool check(int days){

    int temp[n+1];
    for(int i = 0 ;i < n+1 ; i++){

        temp[i] = req[i];

    }

    int curr = 0;
    int dummy = Total;
    for(int i = 1; i <= days ; i++){
        curr++;
        if(sale.find(i) != sale.end()){
            for(auto it : sale[i]){
                if(temp[it] > 0 ){
                    if(temp[it] <= curr){
                        curr -= temp[it];
                        dummy -= temp[it];
                        temp[it] = 0;

                    }
                    if(temp[it] > curr){
                        temp[it] -= curr;
                        dummy -= curr;
                        curr = 0;

                    }
                }
            }
        }
    }
    if(2*dummy <= curr)
        return true;
    return false;
}

const ll Mod = 1e9 + 7;
int main(){
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n >> m;
    for(int i = 1 ; i <= n; i++){
        cin >> c;
        Total += c;
        req[i] = c;
    }
    for(int i = 0 ;i < m ; i++){
        cin >> d >> t;
        sale[d].pb(t);
    }

    int left = 1 , right = 1000000;
    int mn = Mod;
    while(left <= right){
        int mid = (left+right)/2;
        if(check(mid)){
            mn = min(mn , mid);
            right = mid-1;
        }
        else
            left = mid+1;
    }
    cout << mn << endl;
    return 0;
}

#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;

const int N=1e7+10;

int a[N];

bool check(int x){
  int b=0;
  int rem=0;
  for(int days=1;days<=x;days++){
    b++;
    //cout<<a[days]<<" "<<days<<endl;
    if(a[days]>0){
      rem+=(a[days]-min(b,a[days]));
      b-=min(b,a[days]);
    }
    //cout<<days<<" "<<b<<" "<<rem<<endl;
  }
  for(int i=x+1;i<N;i++){
    rem+=a[i];
  }
  rem+=a[0];
  return b>=2*rem;
}

int main(){
  //freopen("input.txt", "r", stdin);
  //freopen("output.txt", "w", stdout);
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n,m;
  cin>>n>>m;
  vector<int> k(n);
  for(int i=0;i<n;i++){
    cin>>k[i];
  }
  vector<int> s(n+1);
  while(m--){
    int d,t;
    cin>>d>>t;
    s[t]=max(s[t],d);
  }
  for(int i=1;i<=n;i++){
    a[s[i]]+=k[i-1];
  }
  int l=1,r=(int)1e7;
  while(r-l>0){
    int mid=(l+r)>>1;
    //cout<<l<<" "<<mid<<" "<<r<<endl;
    if(check(mid))
      r=mid;
    else
      l=mid+1;
  }
  cout<<l<<endl;
  return 0;
}

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

typedef long long int ll;
typedef long double lf;

#define pll pair<ll,ll>
#define vll vector<ll>
#define vpl vector<pair<ll,ll>>
#define mkp  make_pair
#define ppll pair<ll,pair<ll,ll>>
#define pb  push_back

#define ordered_set tree< ll , null_type , less<ll> , rb_tree_tag , tree_order_statistics_node_update >

using namespace __gnu_pbds;
using namespace std;

ll n,m;
map<ll,ll> mp;
map<ll,vll> offers_on_days;

bool go(ll days){
    map<ll,ll> tmp = mp;
    ll money = 0;

    for(int i = 1; i <= days; i++){
        money++;
        vll v = offers_on_days[i];

        for(int j = 0 ; j < v.size(); j++){
            if(money){
                if(tmp[v[j]]){
                    ll buy = min(money , tmp[v[j]]);

                    money -= buy;
                    tmp[v[j]] -= buy;
                }
            }else{
                break;
            }
        }
    }

    for(auto it = tmp.begin(); it != tmp.end(); it++){
        money -= it->second*2;
    }

    return money >= 0;
}

void solve(){
    cin>>n>>m;
    ll low = 1 , high = 0 , mid , d , t , x;
    for(int i = 1 ; i <= n ; i++){
        cin>>x; mp[i] = x;
        high += x*2;
    }
    for(int i = 1 ; i <= m ; i++){
        cin>>d>>t;
        offers_on_days[d].pb(t);
    }
    ll ans = high;
    while(low <= high){
        mid = (low+high)/2;
        if(go(mid)){
            ans = mid;
            high = mid-1;
        }else{
            low  = mid+1;
        }
    }
    cout<<ans;
    //cout<<go(20);
}

int main(){
    ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	ll t = 1;
	//cin>>t;
	while(t--){
	    solve();
	}

}

#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef pair<ll,ll> pll;
typedef set<ll> sll;

bool dec(ll mid,vector<vll>& typetil, vll& antall, ll sum){
    pll tom;
    vector<pll> lengde (typetil.size(),tom);
    for(int i=0;i<typetil.size();i++){
        ll liten=0;
        ll stor=typetil[i].size();
        while(stor-liten>1){
            ll middel=(stor+liten)/2;
            if(typetil[i][middel]>mid){
                stor=middel;
            }
            else{
                liten=middel;
            }
        }
        pll P=make_pair(typetil[i][liten],i);
        lengde[i]=P;
    }
    sort(lengde.begin(),lengde.end());
    ll tilbud=0;
    /*for(int i=0;i<lengde.size();i++){
        cout<<lengde[i].first<<" "<<lengde[i].second+1<<endl;
    }*/
    for(int i=0;i<lengde.size();i++){
        ll penger=lengde[i].first-tilbud;
        ll type=lengde[i].second;
        if(penger<antall[type]){
            tilbud+=penger;
        }
        else{
            tilbud+=antall[type];
        }
    }
    if(mid-tilbud>=2*(sum-tilbud)){
        return true;
    }
    else{
        return false;
    }
}

int main(){
    cin.sync_with_stdio(0);
    cin.tie(0);
    ll n,m;
    cin>>n>>m;
    vector<pll> tilbud;
    vll antall;
    ll sum=0;
    for(int i=0;i<n;i++){
        ll a;
        cin>>a;
        antall.push_back(a);
        sum+=a;
    }
    for(int i=0;i<m;i++){
        ll a,b;
        cin>>a>>b;
        b=b-1;
        pll P=make_pair(a,b);
        tilbud.push_back(P);
    }
    sort(tilbud.begin(),tilbud.end());
    vll tom={0};
    vector<vll> typetil (n,tom);
    for(int i=0;i<m;i++){
        typetil[tilbud[i].second].push_back(tilbud[i].first);
    }
    ll lav=1;
    ll stor=2*sum+1;
    while(stor-lav>1){
        ll mid=(lav+stor)/2;
        if(!dec(mid,typetil,antall,sum)){
            lav=mid;
        }
        else{
            stor=mid;
        }
        //cout<<lav<<" "<<stor<<endl;
        if(stor==2){
            stor=1;
        }
    }
    cout<<stor<<endl;
}

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

ll M=1000000007;

bool is_valid(int x,vector<int> offer[],int b[],int n,int m)
{
    int cost=0;
    int bal=0;
    int a[n];

    for(int i=0;i<n;i++)
    a[i]=b[i];

    for(int d=1;d<=x&&d<=1000;d++)
    {
    	bal=bal+1;
    	for(int j=0;j<offer[d].size()&&bal!=0;j++)
    	{
    		if(a[offer[d][j]-1]==0)
    		continue;

    		int c1=min(a[offer[d][j]-1],bal);

    		bal=bal-c1;
    		cost+=c1;
    		a[offer[d][j]-1]-=c1;
		}
	}

//	cout<<"cost="<<cost<<"\n";
/*	for(int i=0;i<n;i++)
	cout<<a[i]<<" ";
	cout<<"\n";*/
	for(int i=0;i<n;i++)
	{
		cost+=(a[i]*2);
	}

//	cout<<"cost="<<cost<<"\n";

    if(cost<=x)
    return 1;
    return 0;
}

int main()
{
    int n,m;
    cin>>n>>m;
    int a[n];
    vector<int> offers[1003];
    int mxl=0;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        mxl=mxl+a[i]*2;
    }

    for(int i=1;i<=m;i++)
    {
        int u,v;
        cin>>u>>v;
        offers[u].push_back(v);
    }

//	cout<<is_valid(8,offers,a,n,m)<<"\n";

    int res=-1;
    int l=1,r=mxl;
    while(l<=r)
    {
        int mid=l+((r-l)/2);
        if(is_valid(mid,offers,a,n,m))
        {
            r=mid-1;
            res=mid;
        }
        else
        {
            l=mid+1;
        }
    }

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

#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 200010;
const int eps =1e-5;
typedef long long ll;
struct node
{
	ll day,t;
}vis[maxn],las[maxn];
ll last[maxn],num[maxn];
bool cmp(node & a , node & b){return a.day < b.day;}
ll n,m,sum = 0;

bool judge(ll x,ll y){
	memset(last,0,sizeof(last));
	ll i = 0;
	while(vis[i].day <= x){
		last[vis[i].t] = vis[i].day;
		i++;
		if(i == m) break;
	}
	int cnt = 0;
	for(int j = 1 ; j <= n ;j++){
		if(last[j] != 0){
			las[cnt].day = last[j];
			las[cnt].t = j;
			cnt++;
		}
	}
	ll money = 0;
	sort(las,las + cnt,cmp);
	for(int j = 0 ; j < cnt ; j++){
		if(j == 0 ) money += las[j].day;
		else money += las[j].day - las[j - 1].day;
		if(money >= num[las[j].t]){
			money -= num[las[j].t];
			y -= num[las[j].t];
		}else{
			y -= money;
			money = 0;
		}
	}
	money += x - las[cnt - 1].day;
	if(money >= y*2){
		return true;
	}else{
		return false;
	}
}
int main(){
	scanf("%lld %lld",&n,&m);
	for(int i = 1 ; i <= n ;i++){
		scanf("%lld",&num[i]);
		sum += num[i];
	}
	for(int i = 1 ; i <= m ; i++){
		scanf("%lld %lld",&vis[i].day,&vis[i].t);
	}
	sort(vis,vis + m,cmp);
	// int l = 1,r = 2*sum;
	// while(r - l > eps){
	// 	int mid = (l + r)/2;
	// 	if(judge(mid,sum)){
	// 		r = mid;
	// 	}else{
	// 		l = mid + 1;
	// 	}
	// }
	for(int i = 1 ; i <= sum*2 ; i++){
		if(judge(i,sum)){
			printf("%d\n",i);
			break;
		}
	}
	return 0;
}

#include<bits/stdc++.h>
#define ll long long int
#define ull unsigned long long int
#define ld long double
#define pb push_back
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define fo(i,n) for(int i=0;i<n;i++)
#define inp(a) int a;cin>>a;
#define inpa(a,n)fo(i,n)cin>>a[i];
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
using namespace std;

vector<int> dis[400000];
vector<int> a1;
int n;
int count1=0;

bool chk(int d)
{
	vector<int> a=a1;
	int money=d;
	int done=0;
	int prev=0;
	for(int i=d-1;i>=0;i--)
	{
		bool spend=0;
		for(int j:dis[i])
		{
			if(a[j])
			{
				int tp=min(money,a[j]);
				if(tp>0)
				{
					a[j]-=tp;
					money-=tp;
					done+=tp;
					prev+=tp-1;
					spend=1;
				}
			}
		}
		if(spend==0)
		{
			if(prev>0)
			{
				prev--;
			}
			else
			{
				if(money==1)
					money=0;
				else
				{
					prev++;
					money-=2;
					done++;
				}
			}
		}
		//cout<<i<<' '<<money<<','<<done<<endl;
	}
	if(done+money/2>=count1)
		return 1;
	return 0;
}

int main()
{
	fio
	cin>>n;
	inp(m)
	a1.resize(n);
	inpa(a1,n)
	while(m--)
	{
		inp(d) inp(t)
		dis[d-1].pb(t-1);
	}

	fo(i,n)count1+=a1[i];
	//cout<<chk(23);
	//return 0;
	int hi=2*count1,lo=1;
	while(lo<hi)
	{
		int mid=(hi+lo)/2;
		//cout<<mid<<','<<chk(mid)<<'\n';
		if(chk(mid))
		{
			hi=mid;
		}
		else
		{
			lo=mid+1;
		}
	}
	cout<<(hi+lo)/2<<'\n';
}

#include <bits/stdc++.h>

using namespace std;

#define int long long

typedef pair<int,int> ii;
ii q[200001];
int n,m;
int a[200001];
int b[200001];
int lst[200001];
vector<int> z[500001];

bool check(int day)
{
	memset(lst,0,sizeof lst);
	for (int i=1;i<=n;i++)
		b[i] = a[i];
	for (int i=1;i<=m;i++)
		if (q[i].first <= day)
			lst[q[i].second] = max(lst[q[i].second],q[i].first);
	for (int i=1;i<=n;i++)
		if (lst[i] != 0)
			z[lst[i]].push_back(i);
	int cur = 0;
	for (int i=1;i<=day;i++)
	{
		cur++;
		for (int j=0;j<z[i].size();j++)
		{
			int used = min(cur,b[z[i][j]]);
			cur -= used;
			b[z[i][j]] -= used;
		}
		z[i].clear();
	}
	int zz = 0;
	for (int i=1;i<=n;i++)
		zz += b[i];
	return (zz*2 <= cur);
}

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

	cin >> n >> m;
	for (int i=1;i<=n;i++)
		cin >> a[i];
	for (int i=1;i<=m;i++)
		cin >> q[i].first >> q[i].second;
	int l = 0, r = 400000;
	int res;
	while (l < r)
	{
		int mi = (l+r)/2;
		if (check(mi))
		{
			res = mi;
			r = mi-1;
		}
		else
			l = mi+1;
	}
	cout << res;
}

#include <bits/stdc++.h>
using namespace std;
vector <int> a[3001];
int n,m,i,sl[3001],j,k,l,r,kq,c,tg,u,sll[3001],vt[3001],d[3001],t[3001];
bool kt(int x)
{
    memset(vt,0,sizeof(vt));
    for(i=1;i<=n;i++) sl[i]=sll[i];
    for(i=1;i<=m;i++)
        if(d[i]<=x) vt[t[i]]=max(vt[t[i]],d[i]);
    for(i=1;i<=n;i++) a[vt[i]].push_back(i);
    c=0;
    for(i=1;i<=x;i++)
    {
        c++;
        for(j=0;j<a[i].size();j++)
        {
            u=a[i][j];
            tg=min(c,sl[u]);
            c-=tg; sl[u]-=tg;
        }
    }
    for(i=1;i<=n;i++)
    {
        tg=min(c/2,sl[i]);
        c-=tg*2; sl[i]-=tg;
        if(sl[i]>0) return 0;
    }
    return 1;
}
int main()
{
    //freopen("ntu.inp","r",stdin);
    //freopen("ntu.out","w",stdout);
    cin>>n>>m;
    for(i=1;i<=n;i++) { cin>>sl[i]; sll[i]=sl[i]; }
    for(i=1;i<=m;i++)
    {
        cin>>d[i]>>t[i];
        //vt[k]=max(vt[k],j);
    }
    l=1; r=3000;
    while(l<=r)
    {
        int mid=(l+r)>>1;
        if(kt(mid)) { kq=mid; r=mid-1; }
        else l=mid+1;
    }
    cout<<kq;
}

#include<bits/stdc++.h>
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long INT;
typedef pair<int,int> pii;
#define NN 200200
int a[NN],fl[NN],b[NN],c[NN],mx[NN];
pii p[NN];
vector <int> vec[NN],adj[NN];
int main(){
#ifndef ONLINE_JUDGE
	freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
#endif
	int n,m,s=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++) scanf("%d",a+i),s+=a[i];
	for(int i=1;i<=m;i++) scanf("%d%d",&p[i].y,&p[i].x);
	sort(p+1,p+m+1);
	for(int i=1;i<=m;i++) vec[p[i].x].pb(p[i].y);
	int st=0,ed=2*s;
	while(st+1<ed){
		int mid=st+ed>>1;
		for(int i=1;i<=n;i++){
			int r=upper_bound(vec[i].begin(),vec[i].end(),mid)-vec[i].begin();
			if(r>0) adj[vec[i][r-1]].pb(i);
			b[i]=a[i];
		}
		int mo=0;
		for(int i=1;i<=mid;i++){
			mo++;
			for(int v:adj[i]){
				if(mo>a[v]) mo-=a[v],b[v]=0;
				else {b[v]-=mo;mo=0;break;}
			}
		}
		int tt=0;
		for(int i=1;i<=n;i++) tt+=b[i];
		mo-=tt*2;
		if(mo>=0) ed=mid;
		else st=mid;
		for(int i=1;i<=2000;i++) adj[i].clear();
	}
	cout<<ed<<endl;
	return 0;
}

#include <bits/stdc++.h>

using namespace std;

int64_t inf = 1000 * 1000 * 1000;
int64_t inf64 = inf * inf;
int64_t nll = 0;

#define ll long long
#define se second
#define fi first
#define endl '\n'
#define eb emplace_back

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int64_t n, m, sum = 0;
    cin >> n >> m;
    vector <int64_t> a(1005);
    vector <pair<int64_t, int64_t>> b;
    for (int32_t i = 0; i < n; ++i)
    {
        cin >> a[i + 1];
        sum += a[i + 1];
    }
    for (int32_t i = 0; i < m; ++i)
    {
        int64_t x, y;
        cin >> x >> y;
        b.eb(x, y);
    }
    sort(b.begin(), b.end());
    int64_t l = -1, r = 2005;
    vector <int64_t> tmp = a;
    int64_t k = 0;
    while (k < 2005)
    {
        //cout << "---------\n";
        //k = (l + r) / 2;
        int32_t cnt = 0;
        for (int32_t i = 0; i < m; ++i)
        {
            if (b[i].fi <= k)
            {
                while (tmp[b[i].se] > 0)
                {
                    if (b[i].fi > cnt)
                    {
                        ++cnt;
                        --tmp[b[i].se];
                        //cout << b[i].fi << " " << b[i].se << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        //cout << "k: " << k << " - ";
        if ((sum - cnt) * 2 + cnt <= k)
        {
            cout << k;
            break;
            r = k;
            //cout << "good";
        }
        else
        {
            l = k;
            //cout << "bad";
        }
        //cout << endl;
            ++k;
        tmp = a;
    }
    //cout << r;
}
/*

*/

#include <bits/stdc++.h>

#define ll long long

int main() {
    using namespace std;
    ll n, m, a, b, c, s;
    cin >> n >> m;
    vector<ll> A(n + 1, 0);
    const int max_day = 200'000;
    vector< vector<int> > item_sales(n + 1), day_sales(max_day + 1);
    for(int i = 1; i <= n; i++) cin >> A[i];
    s = accumulate(A.begin(), A.end(), 0);

    for(int i = 0; i < m; i++) {
        cin >> a >> b;
        item_sales[b].push_back(a);
        day_sales[a].push_back(b);
    }

    for(int i = 0; i < n; i++)
        sort(item_sales[i].begin(), item_sales[i].end());

    for(int i = 0; i < n; i++)
        item_sales[i].erase(unique(item_sales[i].begin(), item_sales[i].end()), item_sales[i].end());

    /*
    for(int i = 0; i < A.size(); i++)
        cout << A[i] << " ";
    cout << "\n";
    cout << "\n";
    cout << "\n";
    */

    a = 0; b = 2 * s;
    while(a < b) {
        c = (a + b) / 2;
        vector<ll> B(A);
        vector<int> item_sales_index(n + 1, 0);
        ll bourles = 0;
        for(int d = 1; d <= c; d++) {
            bourles += 1;
            if(d > max_day) continue;
            for(int j = 0; j < day_sales[d].size() && bourles > 0; j++) {
                int item = day_sales[d][j];
                if(B[item] == 0) continue;
                if(item_sales_index[item] + 1 == item_sales[item].size() ||
                        item_sales[item][item_sales_index[item] + 1] > c) {
                    int to_spend = min(bourles, B[item]);
                    bourles -= to_spend;
                    B[item] -= to_spend;
                } else if(item_sales_index[item] < item_sales[item].size()) {
                    item_sales_index[item] += 1;
                }
            }
        }
        /*
        cout << "c = " << c << "\n";
        for(int i = 0; i < B.size(); i++)
            cout << B[i] << " ";
        cout << "\n";
        */
        if(2 * accumulate(B.begin(), B.end(), 0) <= bourles)
            b = c;
        else
            a = c + 1;
    }
    cout << a << "\n";
    return 0;
}

#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

typedef long long ll;
typedef long double ld;
#define PI 3.14159265358979323846
ll MOD = 1e9 + 7;
ld eps = 1e-7;
seed_seq seq{ (uint64_t) chrono::duration_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count(), (uint64_t) __builtin_ia32_rdtsc(), (uint64_t) (uintptr_t) make_unique<char>().get() };
mt19937 rng(seq);
typedef tree <ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
inline ll nxt() {
    ll x;
    scanf("%d", &x);
    return x;
}
ll st(ll t, ll id, ll mod){
    ll res = 1, a = t, n = id;
    while (n) {
        if (n & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        n >>= 1;
    }
    return res % mod;
}
ll del(ll a, ll b){
    return (a * st(b, MOD - 2, MOD)) % MOD;
}
#define sz(q) q.size()
const int NN = 500002;
typedef long long integer;

#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
gp_hash_table<int, int> memo;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll n, m;
    cin >> n >> m;
    ll k[n];
    ll k2[n];
    ll sm = 0;
    for (int i = 0; i < n; i++){
        cin >> k[i];
        k2[i] = k[i];
        sm += k[i];
    }
    vector<pair<ll, ll> > d;
    for (int i = 0; i < m ; i++){
        ll tp, dy;
        cin >> dy >> tp;
        tp--;
        if (k2[tp]){
            d.push_back({dy, tp});
            k2[tp]--;
        }
    }
    sort(d.begin(), d.end());
    ll L = 0, R = 400000;
    while(R - L > 1){
        ll k3[n];
        for (int i = 0; i < n; i++){
            k3[i] = k[i];
        }
        ll mid = (R + L) / 2;
        ll hav = 0, isp = 0, lst = 0;
        ll lstt[n];
        for (int i = 0; i < n; i++){
            lstt[i] = 0;
        }
        for (auto i : d){
            if (i.first <= mid){
                lstt[i.second] = i.first;
            }
        }

        vector<pair<ll, ll> > d2;
        for (int i = 0; i < n; i++){
            if (lstt[i]){
                d2.push_back({lstt[i], i});
            }
        }
        sort(d2.begin(), d2.end());
        for (auto i : d2){
            if (i.first > mid){
                break;
            }
            hav += i.first - lst;
            lst = i.first;
            ll ber = min(k3[i.second], hav);
            hav -= ber;
            isp += ber;
            k3[i.second] -= ber;
        }
        sm = 0;
        for (int i = 0; i < n; i++){
            sm += k3[i];
        }
        hav = mid - isp;
        if (hav >= 2 * sm){
            R = mid;
        }
        else{
            L = mid;
        }
    }
    ll k3[n];
    for (int i = 0; i < n; i++){
        k3[i] = k[i];
    }
    ll mid = R - 1;
    ll hav = 0, isp = 0, lst = 0;
    ll lstt[n];
    for (int i = 0; i < n; i++){
        lstt[i] = 0;
    }
    for (auto i : d){
        if (i.first <= mid){
            lstt[i.second] = i.first;
        }
    }

    vector<pair<ll, ll> > d2;
    for (int i = 0; i < n; i++){
        if (lstt[i]){
            d2.push_back({lstt[i], i});
        }
    }
    sort(d2.begin(), d2.end());
    for (auto i : d2){
        if (i.first > mid){
            break;
        }
        hav += i.first - lst;
        lst = i.first;
        ll ber = min(k3[i.second], hav);
        hav -= ber;
        isp += ber;
        k3[i.second] -= ber;
    }
    sm = 0;
    for (int i = 0; i < n; i++){
        sm += k3[i];
    }
    hav = mid - isp;
    if (hav >= 2 * sm) {
        cout << R - 1;
    }
    else{
        cout << R;
    }

}
//cout.precision(20);
//clock_t time
//time = clock();
//while((double)(clock() - time)/CLOCKS_PER_SEC < 3.95) {
//rng() % n
//8
//0 7 2 5 4  3 6 1

/*
 10 8
9 2 8798
2 6 9369
9 5 9133
4 9 8909
3 10 8884
7 3 8342
3 7 9225
9 4 8040

 */

#include <bits/stdc++.h>
using namespace std;
#define testing 1
#define FOR(i,s,e) for(ll i = s; i <= (ll)e; ++i)
#define DEC(i,s,e) for(ll i = s; i >= (ll)e; --i)
#define IAMSPEED ios_base::sync_with_stdio(false); cin.tie(0);
#define db(x) cerr << #x << "=" << x << "\n"
#define db2(x, y) cerr << #x << "=" << x << " , " << #y << "=" << y << "\n"
#define db3(a,b,c) cerr<<#a<<"="<<a<<","<<#b<<"="<<b<<","<<#c<<"="<<c<<"\n"
#define dbv(v) cerr << #v << ":"; for (auto ite : v) cerr << ite << ' '; cerr <<"\n"
#define dbvp(v) cerr << #v << ":"; for (auto ite : v) cerr << "{"  << ite.f << ',' << ite.s << "} "; cerr << "\n"
#define dba(a,ss,ee) cerr << #a << ":"; FOR(ite,ss,ee) cerr << a[ite] << ' '; cerr << "\n"
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define f first
#define s second
#define reach cerr << "LINE: " << __LINE__ << "\n";
typedef pair <int, int> pi;
typedef tuple<int,int,int> ti3;
string cts(char x) {string t(1,x); return t;}
ll rand(ll a, ll b) { return a + rng() % (b-a+1); }
const int MOD = 1e9 + 7;
const int inf = (int)1e9 + 500;
const long long oo = (ll)1e18 + 500;
template <typename T> void chmax(T& a, T b) { a = max(a, b); }
template <typename T> void chmin(T& a, T b) { a = min(a, b); }
#define MAXN 200005
#if !testing
#define cerr if(0)cout
#endif
int n,m;
int A[MAXN];
int idx[MAXN];
vector<int>V[MAXN];
ll total;
bool check(int days) {
	vector<int>events[MAXN];
	unordered_set<int>done;
	FOR(i,1,n) {
		if(V[i].empty())continue;
		auto it = upper_bound(all(V[i]),days);
		if(it!=V[i].begin())--it;
		if(*it<=days){
		    events[*it].pb(A[i]);
		    done.insert(i);
		}
	}
	int burles = 0;
	int extra = 0;

	FOR(i,1,days) {
	 	++burles;
		if(days>=MAXN)continue;
		for(auto v:events[i]) {
			if(v<=burles) {
				burles-=v;
				v = 0;
			} else {
				v-=burles;
				burles = 0;
				extra += v;
			}
		}
	}
	FOR(i,1,n) {
	    if(!done.count(i))extra+=A[i];
	}
	return burles >= extra*2;
}

int32_t __attribute__((optimize("Ofast"), target("arch=sandybridge"))) main()
{
	IAMSPEED
	FOR(i,1,n)idx[i]=0;
	cin >> n >> m;
	FOR(i,1,n){
		cin>>A[i];
	}
	FOR(i,1,m) {
		int d,t; cin >> d >> t;
		V[t].pb(d);
	}
	FOR(i,1,2e5){
		sort(all(V[i]));
	}
	//given a certain date, use the latest deal that is <= the date
	int lo = 0, hi = 2*MAXN;
	while(lo < hi-1) {
		int mid = (lo + hi) / 2;
		if(check(mid)) hi = mid;
		else lo = mid;
		reach
	}
	cout<<hi;
}

#include <bits/stdc++.h>
#define ll long long
#define met(a, b) memset(a, b, sizeof(a))

using namespace std;

const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;

int rd() {
    int sum = 0, flag = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9') {
        if(ch == '-') flag = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9') {
        sum = (sum << 1) + (sum << 3) + ch - '0';
        ch = getchar();
    }
    return sum*flag;
}
ll RD() {
    ll sum = 0, flag = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9') {
        if(ch == '-') flag = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9') {
        sum = (sum << 1) + (sum << 3) + ch - '0';
        ch = getchar();
    }
    return sum*flag;
}
#define int ll
struct node {
    int d, t;
}arr[200010];

int N[200010];

bool cmp(node a, node b) {
    return a.d < b.d;
}
#undef int
int main() {
    #define int ll
    int n = RD();
    int m = RD();
    int all = 0;
    for(int i = 1; i <= n; i++) {
        N[i] = RD();
        all += N[i];
    }
    for(int i = 1; i <= m; i++) {
        arr[i].d = RD();
        arr[i].t = RD();
    }
    sort(arr+1, arr+1+m, cmp);
    int day = 0;
    int sum = 0;
    for(int i = 1; i <= m; i++) {
        if(arr[i].d > day) {
            sum += arr[i].d-day;
            day = arr[i].d;
        }
        if(sum / 2 >= all) {
            day -= sum-2*all;
            break;
        }
        if(N[arr[i].t]) {
            if(sum > N[arr[i].t]) {
                sum -= N[arr[i].t];
                all -= N[arr[i].t];
                N[arr[i].t] = 0;
            }
            else {
                N[arr[i].t] -= sum;
                all -= sum;
                sum = 0;
            }
        }
        if(sum / 2 >= all) {
            all = 0;
            break;
        }
    }
    if(all) day += all*2-sum;
    cout << day << endl;
    return 0;
}

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

#define lp(var,start,end) for (ll var = start; var <end ; ++var)
#define rlp(var,start,end) for(ll var = start; var>=end ; var--)
#define pb push_back
#define mp make_pair
#define pf push_front
#define ff first
#define ss second
#define vll vector<ll>
#define vld vector<ld>
#define pll pair<ll,ll>
#define pld pair<ld,ld>
#define vpll vector<pll>
#define vpld vector<pld>

#define all(X) X.begin(),X.end()
#define endl "\n"

const ll N=1e5+5;

int main()
{
    //ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
	ll n,m;
	cin >> n >> m;
	ll ary[n];
	ll c=0;
	lp(i,0,n)
	{
		cin >> ary[i];
		c+=ary[i];
	}
	vll G[2*N+1];
	lp(i,0,m)
	{
		ll a,b;
		cin >> a >> b;
		G[a].pb(b-1);
	}
	ll lo=0;
	ll hi=1e9;
	while(hi>lo)
	{
		ll mid=(hi+lo)/2;
		ll tmp[n];
		lp(i,0,n)
		{
			tmp[i]=ary[i];
		}
		ll mon=mid;
		ll sur=0;
		rlp(i,2*N,0)
		{
			if(mon>i)
			{
				sur+=mon-i;
				mon=i;
			}
			if(i==0)break;
			lp(j,0,G[i].size())
			{
				ll x=G[i][j];
				if(tmp[x]>0)
				{
					if(tmp[x]>mon)
					{
						tmp[x]-=mon;
						mon=0;
					}
					else if(mon>=tmp[x])
					{
						mon-=tmp[x];
						tmp[x]=0;
					}
				}
			}
		}
		ll f=0;
		lp(i,0,n)
		{
			if(tmp[i]>0)
			{
				if(sur>=2*tmp[i])
				{
					sur-=2*tmp[i];
					tmp[i]=0;
				}
				else
				{
					f=1;
				}
			}
		}
		if(f==1)
		{
			lo=mid+1;
		}
		else
		{
			hi=mid;

		}
	}
	cout<<lo<<endl;
	return 0;
}

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

ll M=1000000007;

bool is_valid(int x,vector<int> offer[],int b[],int n,int m)
{
    int cost=0;
    int bal=0;
    int a[n];

    for(int i=0;i<n;i++)
    a[i]=b[i];

    for(int d=1;d<=x;d++)
    {
    	bal=bal+1;
    	if(d>1000)
    	continue;

    	for(int j=0;j<offer[d].size()&&bal!=0;j++)
    	{
    		if(a[offer[d][j]-1]==0)
    		continue;

    		int c1=min(a[offer[d][j]-1],bal);

    		bal=bal-c1;
    		cost+=c1;
    		a[offer[d][j]-1]-=c1;
		}
	}

//	cout<<"cost="<<cost<<"\n";
/*	for(int i=0;i<n;i++)
	cout<<a[i]<<" ";
	cout<<"\n";*/
	int c2=0;
	for(int i=0;i<n;i++)
	{
		c2=c2+a[i]*2;
	}
	if(c2<=bal)
	return 1;
//	cout<<"cost="<<cost<<"\n";

    return 0;
}

int main()
{
    int n,m;
    cin>>n>>m;
    int a[n];
    vector<int> offers[1003];
    int mxl=0;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        mxl=mxl+a[i]*2;
    }

    for(int i=1;i<=m;i++)
    {
        int u,v;
        cin>>u>>v;
        offers[u].push_back(v);
    }

//	cout<<is_valid(8,offers,a,n,m)<<"\n";

    int res=-1;
    int l=1,r=mxl;
    for(int i=1;i<=mxl;i++)
    {
    	if(is_valid(i,offers,a,n,m))
    	{
			res=i;
			break;
		}

	}

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

#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#include <intrin.h>

using namespace std;

typedef long long ll;

const int sz = 2e5 + 1;

int n, m;
int v[sz], o[sz];
vector<int> d[sz];
vector<int> pref[sz];

bool ok(int md) {
	memset(o, 0, sizeof(o));
	int cur = 0;
	for (int i = 1; i < min(md + 1, sz); i++) {
		cur++;
		for (int j = 0; j < d[i].size(); j++) {
			int cnt = min(v[d[i][j]] - o[d[i][j]], cur);
			o[d[i][j]] += cnt;
			cur -= cnt;
		}
	}

	for (int i = 1; i <= n; i++) {
		int cnt = min(cur / 2, v[i] - o[i]);
		o[i] += cnt;
		cur -= cnt * 2;
		if (o[i] != v[i])
			return 0;
	}

	return 1;
}

inline void solve() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		cin >> v[i];
	}
	for (int i = 0; i < m; i++) {
		int a, b;
		cin >> a >> b;
		d[a].push_back(b);
		pref[b].push_back(a);
	}

	for (int i = 0; i < sz; i++)
		sort(pref[i].begin(), pref[i].end());

	for (int i = 0; i < sz; i++) {
		random_shuffle(d[i].begin(), d[i].end());
	}

	int l = 0, r = 3e5 + 2;
	int md;
	while (l <= r) {
		md = l + (r - l) / 2;
		bool res = ok(md);
		if (res)
			r = md - 1;
		else
			l = md + 1;
	}

	cout << l;
}

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
#if defined(_DEBUG)
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int q = 1;
	//cin >> q;
	for (; q > 0; q--) {
		solve();
		cout << '\n';
	}
}