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>

using namespace std;

int main()
{
  int P, R, T, L[300], N[300][300];
  int latte[200000], malta[200000];


  cin >> P >> R >> T;
  for(int i = 0; i < R; i++) {
    cin >> L[i];
  }
  for(int i = 0; i < P; i++) {
    for(int j = 0; j < R; j++) {
      cin >> N[i][j];
    }
  }
  for(int i = 0; i < T; i++) {
    cin >> latte[i] >> malta[i];
    --latte[i];
    --malta[i];
  }

  int ok = -1, ng = T;
  while(ng - ok > 1) {
    int mid = (ok + ng) / 2;
    ([&]
     {
       vector< vector< int > > need(P, vector< int >(R));
       vector< int > available(R);
       for(int i = 0; i < P; i++) {
         for(int j = 0; j < R; j++) need[i][j] = N[i][j];
       }
       for(int i = 0; i < R; i++) available[i] = L[i];

       for(int i = 0; i <= mid; i++) {
         --need[latte[i]][malta[i]];
         --available[malta[i]];
       }

       vector< int > live(P);
       iota(begin(live), end(live), 0);

       int sum = 0;
       while(!live.empty()) {
         vector< int > nxt;
         bool update = false;
         for(int i : live) {
           bool f = true;
           for(int j = 0; j < R; j++) {
             if(need[i][j] == 0) continue;
             f &= need[i][j] <= available[j];
           }
           if(f) {
             update = true;
             for(int j = 0; j < R; j++) available[j] += N[i][j] - need[i][j];
           } else {
             nxt.push_back(i);
           }
         }
         if(!update) return (false);
         swap(nxt, live);
       }
       return (true);
     }() ? ok : ng) = mid;
  }
  if(ok >= T - 1) cout << -1 << endl;
  else cout << ok + 2 << endl;
}