Official

B - Maintain Multiple Sequences Editorial by en_translator


This problem is a exercise for two-dimensional array. The knowledge is required many times for solving problems in AtCoder, so we recommend you to take this chance to learn it.


Solution in C++

First, declare a two-dimensional std::vector.

vector<vector<int>> a(n);

This means that you “declare a two-dimensional std::vector consisting of n empty std::vector<int>s.” Each element of a signifies a one-dimensional std::vector.

Then, receive the input:

for (int i = 0; i < n; ++i) {
  int l;
  cin >> l;
  a[i].resize(l);
  for (int j = 0; j < l; ++j) {
    cin >> a[i][j];
  }
}

Initially, a[i] is an empty sequence. In order to store \(L_i\) integers, you need to reserve a space to store them. In the \(4\)-th line, we call std::vector::resize to prepare a capacity of storing l integers.

Note that the \(4\)-th line can be written as follows:

a[i] = vector<int>(l);

This means that you “assign a std::vector<int> of size l into a[i].”

Since the indices are 0-based, a[i - 1][j - 1] signifies the \(j\)-th element of the \(i\)-th sequence. Thus, you can answer the given queries.

Sample code


Solution in Python

Python has a data structure called list. Let us use a two-dimensional array to manage the sequence:

a = [[] for _ in range(n)]

This means that you “declare a list consisting of n empty lists.”

Then you receive the input:

for i in range(n):
  a[i] = list(map(int, input().split()))

This means that you “receive the entire line and make a one list.” Therefore, a[i] has \(L_i + 1\) elements \((L_i, a_{i, 1}, \dots, a_{i, L_i})\).

Therefore, a[i - 1][j] signifies the \(j\)-th term of the \(i\)-th sequence. Thus, you can answer the given queries.

Sample code

posted:
last update: