B - ゲストリストの管理 / Managing the Guest List 解説 by admin
Qwen3-Coder-480BOverview
This problem requires efficiently managing registered guest numbers and quickly determining whether a given number has already been registered.
Analysis
In this problem, up to \(4 \times 10^5\) operations are given, and for each operation we need to do one of the following:
- Add a guest number to the guest list (no duplicates)
- Check whether a given guest number already exists in the list
A naive approach would be to manage the list using a list or array, but searching for an element would take \(O(N)\), resulting in a worst-case overall complexity of \(O(Q^2)\), which is too slow (TLE).
Therefore, we need a data structure that can perform insertions and lookups efficiently. In Python, by using a set, both insertion and lookup can be performed in \(O(1)\) on average. This is implemented based on a hash table and is very efficient.
Additionally, for reading input, using the standard input() function is slow, so we speed things up by reading all input at once using sys.stdin.read().
Algorithm
- Read all input at once and create a list of queries.
- Prepare a
set-type variableguest_setto manage the numbers of arrived guests. - For each query, do the following:
- When \(T_i = 1\): Add \(X_i\) to
guest_set. - When \(T_i = 2\): Determine whether \(X_i\) is contained in
guest_set, and record the result.
- When \(T_i = 1\): Add \(X_i\) to
- After processing all queries, output the
Yes/Noresults separated by newlines.
Example
Suppose the input is as follows:
5
1 100
2 100
1 200
2 100
2 300
Processing flow:
- Operation 1: Add 100 →
guest_set = {100} - Operation 2: 100 exists →
Yes - Operation 3: Add 200 →
guest_set = {100, 200} - Operation 4: 100 exists →
Yes - Operation 5: 300 does not exist →
No
Output:
Yes
Yes
No
Complexity
- Time complexity: \(O(Q)\)
- Space complexity: \(O(Q)\)
Since each operation can be processed in \(O(1)\) on average, the overall time is linear.
Implementation Notes
To achieve fast I/O in Python, use
sys.stdin.read.To perform fast existence checks and insertions, use a
set.Collecting all results and outputting them at the end can further improve performance.
Source Code
import sys
input = sys.stdin.read
guest_set = set()
result = []
data = input().split()
Q = int(data[0])
queries = [(int(data[i*2+1]), int(data[i*2+2])) for i in range(Q)]
for T, X in queries:
if T == 1:
guest_set.add(X)
else:
if X in guest_set:
result.append("Yes")
else:
result.append("No")
print("\n".join(result))
This editorial was generated by qwen3-coder-480b.