Problem: Example

Input

2 2 7
3 4
3 2
1 3
1 1
2 2
1 2
2 1
1 2
2 2
1 1


Output

5

Solution (in CPP):

Solution:
#include <bits/stdc++.h>

#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)

#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)

#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
#define popcount(n) (__builtin_popcountll(n))

using namespace std;

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

using ll=long long;
using R=long double;
const R EPS=1e-9; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7
inline int sgn(const R& r){return(r > EPS)-(r < -EPS);}
inline R sq(R x){return sqrt(max<R>(x,0.0));}

const int dx[8]={1,0,-1,0,1,-1,-1,1};
const int dy[8]={0,1,0,-1,1,1,-1,-1};

// Problem Specific Parameter:

int p,r,t;
int l[310];
int need[310][310];
int proc[200010],res[200010];

bool avoid(int t){
	int cl[310],cur[310][310];
	bool term[310];
	
	rep(i,p)rep(j,r) cur[i][j]=0;
	rep(j,r) cl[j]=l[j];

	rep(i,t){
		cur[proc[i]][res[i]]++,cl[res[i]]--;
		term[proc[i]]=true;
		rep(j,r) if(cur[proc[i]][j]!=need[proc[i]][j]) term[proc[i]]=false;
		if(term[proc[i]]) rep(j,r) cl[j]+=need[proc[i]][j],cur[proc[i]][j]=0;
	}

	/*
	cout << need[0][0]-cur[0][0] << " " << need[0][1]-cur[0][1] << endl;
	cout << need[1][0]-cur[1][0] << " " << need[1][1]-cur[1][1] << endl;
	cout << cl[0] << " " << cl[1]  << endl;
	*/

	rep(loop,p){
		bool can=false;

		rep(i,p){
			if(term[i]) continue;
			bool ok=true;
			rep(j,r) if(need[i][j]-cur[i][j]>cl[j]) ok=false;
			
			if(ok==false) continue;
			can=true,term[i]=true;
			rep(j,r) cl[j]+=cur[i][j],cur[i][j]=0;
		}

		if(can==false) break;
	}

	rep(i,p) if(term[i]==false) return false;
	return true;
}

int main(void){
	cin >> p >> r >> t;
	rep(i,r) cin >> l[i];
	rep(i,p)rep(j,r) cin >> need[i][j];
	rep(i,t) cin >> proc[i] >> res[i],proc[i]--,res[i]--;

	int lb=0,ub=t+1;
	while(abs(ub-lb)>1){
		const int mid=(lb+ub)/2;
		if(avoid(mid))
			lb=mid;
		else
			ub=mid;
	}

	//rep(i,1,t+1) cout << i << " : " << (avoid(i)?"Avoid":"Unavoid") << endl;
	cout << (ub==t+1?-1:ub) << endl;
	return 0;
}