Official

B - Reverse Proxy Editorial by en_translator


If \(X_i \ge 1\), put the ball into box \(X_i\).

If \(X_i = 0\), you can determine which box to put the ball into using a for statement.
Once you spotted the box to put the ball in, all that left is to actually put the ball into box, just as \(X_i \ge 1\) cases.

If \(X_i \ge 1\), it can be processed with a constant number of operations; if \(X_i = 0\), it requires about \(O(N)\) operations. Hence, the overall time complexity is \(O(NQ)\).

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int N,Q;
  cin >> N >> Q;
  vector<int> bk(N+1,0);
  for(int i=0;i<Q;i++){
    if(i){cout << " ";}

    int X;
    cin >> X;
    if(X>=1){
      bk[X]++;
      cout << X;
    }
    else{
      int y=1;
      for(int j=2;j<=N;j++){
        if(bk[y]>bk[j]){ y=j; }
      }
      bk[y]++;
      cout << y;
    }
  }
  cout << "\n";
  return 0;
}

Bonus! Can you solve this problem in \(O(NQ)\) time?

posted:
last update: