Official

B - Vacation Together Editorial by en_translator


First of all, let us divide the problem into parts.
First, in order to solve this problem, we have to answer the following question: “is everyone free on the \(j\)-th day?” To determine it, it is sufficient to check for each \(j\) if \(S_{i, j}\) is all o for all \(i=1,2,\dots,N\), which can be found in an \(\mathrm{O}(ND)\) by scanning with a for loop.

Suppose that the answers to the questions are in a string \(T\) (whose the \(j\)-th character is o when everybody is free and x when not); then answer to the problem equals:

How many consecutive os occur in a length-\(D\) string \(T\)?

This can be solved in a total of \(\mathrm{O}(D)\) time with the following algorithm. (It is a good idea to remember the solution, as it is typical.)

  • Let \(\mathrm{ans}\) be a variable to store the maximum consecutive occurrences of o. Initially, \(\mathrm{ans} = 0\).
  • Also, (supposing that the string is scanned from left to right) let \(\mathrm{cur}\) be the number of consecutive os at the last of the string that we have scanned so far. Initially, \(\mathrm{cur} = 0\).
  • For \(i=1, 2, \dots, D\), do the following:
    • If \(T[i] =\) o, update \(\mathrm{cur}\) to \(\mathrm{cur} + 1\), as the number of trailing os increases by one.
    • If \(T[i] =\) x, set \(\mathrm{cur}\) to \(0\), as the last character is x.
  • Finally, set \(\mathrm{ans}\) to \(\max(\mathrm{ans}, \mathrm{cur})\).

There are other ways, but without cautions the complexity might bloat to \(\mathrm{O}(D^2)\) or \(\mathrm{O}(D^3)\), which may cause TLE (Time Limit Exceeded) under a large constraints. (In this problem, \(D \leq 100\), so there is nothing to worry.)

Therefore, the problem has been solved in a total of \(\mathrm{O}(ND)\) time, which is fast enough.

  • Sample code in C++ (in this sample code, we do not actually construct \(T\); instead, we find the answer to the question one by one while scanning each character, while updating the values \(\mathrm{ans}\) and \(\mathrm{cur}\).
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
  int N, D;
  cin >> N >> D;
  vector<string> S(N);
  for (auto& s : S) cin >> s;

  int ans = 0, cur = 0;
  for (int j = 0; j < D; j++) {
    int can = 1;
    for (int i = 0; i < N; i++) {
      can &= S[i][j] == 'o';
    }
    if (can) {
      cur++;
    } else {
      cur = 0;
    }
    ans = max(ans, cur);
  }
  cout << ans << "\n";
}

posted:
last update: