A - 数値列の一致 / Matching Sequences 解説 by admin
Claude 4.6 Opus (Thinking)Overview
This problem asks you to find the minimum number of operations needed to make two numerical sequences \(A\) and \(B\) identical. The answer is obtained by calculating the absolute difference between \(A_i\) and \(B_i\) for each index and summing them up.
Analysis
Key Insight
For each index \(i\), we want to make \(A_i\) and \(B_i\) equal. In one operation, we can increase or decrease either \(A_i\) or \(B_i\) by \(1\) for a chosen index \(i\).
The key point here is that different indices are independent of each other. An operation on index \(i\) does not affect the values at index \(j\) (\(i \neq j\)). Therefore, we can compute the minimum number of operations for each index separately and sum them all up.
Minimum Number of Operations at Each Index
For index \(i\), the difference between \(A_i\) and \(B_i\) is \(|A_i - B_i|\). To reduce this difference to \(0\), regardless of whether we increase/decrease \(A_i\) or increase/decrease \(B_i\), each operation reduces the difference by exactly \(1\).
For example, if \(A_i = 3\), \(B_i = 7\): - The difference is \(|3 - 7| = 4\) - Increasing \(A_i\) four times to make it \(7\), decreasing \(B_i\) four times to make it \(3\), or increasing \(A_i\) twice and decreasing \(B_i\) twice to make both \(5\) — any method requires exactly \(4\) operations.
In other words, the minimum number of operations at index \(i\) is \(|A_i - B_i|\).
Comparison with a Naive Approach
Since this problem is essentially simple, the naive approach (computing the absolute difference at each index and summing them up) directly gives the optimal solution. There are no complex traps to worry about regarding TLE or WA, but note that the value of \(A_i - B_i\) can be up to \(2 \times 10^9\), so the total can become large (in Python, there is no integer overflow).
Algorithm
- Read \(N\) and the numerical sequences \(A\), \(B\).
- For each \(i = 1, 2, \dots, N\), compute \(|A_i - B_i|\).
- Output the sum \(\displaystyle \sum_{i=1}^{N} |A_i - B_i|\).
Complexity
- Time complexity: \(O(N)\) — only constant-time computation is performed for each index.
- Space complexity: \(O(N)\) — for storing the numerical sequences \(A\), \(B\).
Implementation Notes
In Python, using
zip(A, B)allows you to simultaneously iterate over corresponding elements of \(A\) and \(B\), making the code concise.Python supports arbitrary-precision integers, so there is no concern about overflow even if the total becomes large.
When implementing in languages with fixed-width integers such as C++, the total can reach up to \(N \times 2 \times 10^9 = 4 \times 10^{14}\), so you need to use the
long longtype.Source Code
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print(sum(abs(a - b) for a, b in zip(A, B)))
This editorial was generated by claude4.6opus-thinking.
投稿日時:
最終更新: