Official

B - Arrays Editorial by en_translator


This is an exercise of variable-length arrays. Data structures like list in Python and vector in C++ behave as a “variable-length array” by default, where memory is reserved dynamically (on-demand).

If we try to use an \(N \times M\) (fixed-dimension) array, inputs like \(L = (10^5 , 1, 1, \ldots , 1)\) will require \(10^5\)-by-\(10^5\) two-dimensional array, which is likely to cause MLE (Memory Limit Exceeded).

However, if we store the sequences in variable-length arrays, each will be only as long as necessary. Since the sum of numbers of elements (sum of \(L_i\)) is guaranteed to be \(\le 2 \times 10^5\) by Constraints, they can be managed within the size of memory limit.

For more details, please refer to sample code.

Sample code in Python

n = int(input())
a = []
for _ in range(n):
    row = list(map(int, input().split()))
    a.append(row[1:]) # Append only as many as needed

x, y = map(int, input().split())
print(a[x-1][y-1])

C++ の実装例

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n; cin >> n;

    vector<vector<int>> a(n);
    for (int i=0; i<n; i++) {
        int l; cin >> l;
        a[i].resize(l); // Reserve only as many as needed
        for (int j=0; j<l; j++) {
            cin >> a[i][j];
        }
    }
    
    int x, y; cin >> x >> y;
    cout << a[x-1][y-1] << endl;
    
    return 0;
}

posted:
last update: