A - 本棚の整理 / Organizing the Bookshelf 解説 by admin
GPT 5.2 HighOverview
For each book, determine whether “the number of times read \(C_i\) is at most \(K\)”, and sum up the satisfaction values \(D_i\) of the books that satisfy the condition.
Analysis
What we want is “the sum of \(D_i\) when selecting all books with \(C_i \le K\)”, so no optimization of selection or sorting is needed at all. Each book can be judged independently — if it satisfies the condition, add it; if not, ignore it. That’s all we need to get the answer.
What needs to be done is straightforward, but since \(N \le 2 \times 10^5\) is large, implementations with slow input processing (e.g., calling input() every time, storing everything in unnecessary data structures, etc.) may face time constraints depending on the environment.
Therefore, we adopt an approach of reading all input at once for speed and accumulating the sum on the fly during traversal (avoiding unnecessary storage).
Example: If \(K=3\) and the books are \((C,D)=(1,10),(5,7),(3,4)\), then the books satisfying the condition are those with \(C=1,3\), so the total is \(10+4=14\).
Algorithm
- Read \(N, K\)
- Initialize
total = 0 - For \(i=1\) to \(N\):
- Read \((C_i, D_i)\)
- If \(C_i \le K\), then
total += D_i
- Output
total(If no books qualify, nothing is added andtotalremains0, which is still correct)
Complexity
- Time complexity: \(O(N)\) (just checking each book once)
- Space complexity: \(O(1)\) (only a constant number of variables such as the total)
Implementation Notes
In Python, using bulk reading such as
sys.stdin.buffer.read().split()for fast input is recommended for stability.The total can be as large as approximately \(2 \times 10^{14}\), but since Python’s
intsupports arbitrary precision, there is no concern about overflow.Source Code
import sys
def main():
it = iter(sys.stdin.buffer.read().split())
N = int(next(it))
K = int(next(it))
total = 0
for _ in range(N):
c = int(next(it))
d = int(next(it))
if c <= K:
total += d
sys.stdout.write(str(total))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: