Official
B - First Query Problem Editorial by en_translator
A query problem like this requires an “efficient simulation in response to an on-line query” or an “avoiding naive application of operations by prefetching the queries.”
In this problem, one can use an array to solve this problem (while processing the queries on-line.)
Specifically, in C++, you can use a raw array or a std::vector
, and in Python, a list, to solve this problem.
A sample code is below. When implementing, note that the number of input values differs depending on the query type.
C++ (raw array)
#include <iostream>
using namespace std;
int A[100000];
int main() {
int N;
cin >> N;
// Receive A
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
int Q;
cin >> Q;
// Receive queries
for (int i = 0; i < Q; ++i) {
int type;
cin >> type;
if (type == 1) {
// Update A if the query is of 1-st type
int k, x;
cin >> k >> x;
A[k - 1] = x;
} else {
// Print A if the query is of 2-nd type
int k;
cin >> k;
cout << A[k - 1] << endl;
}
}
return 0;
}
C++ (std::vector
)
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> A(N);
// Receive A
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
int Q;
cin >> Q;
// Receive the queries
for (int i = 0; i < Q; ++i) {
int type;
cin >> type;
if (type == 1) {
// Update A if the query is of 1-st type
int k, x;
cin >> k >> x;
A[k - 1] = x;
} else {
// Print A if the query is of 2-nd type
int k;
cin >> k;
cout << A[k - 1] << endl;
}
}
return 0;
}
python
N = int(input())
# Receive A
A = list(map(int, input().split()))
Q = int(input())
# Receive the queries
for i in range(Q):
query = list(map(int, input().split()))
if query[0] == 1:
# Update A if the query is of 1-st type
type, k, x = query
A[k - 1] = x
else:
# Print A if the query is of 2-nd type
type, k = query
print(A[k - 1])
posted:
last update: