A - 数値列の一致 / Matching Sequences 解説 by admin 印刷ページ
GPT 5.2 HighOverview
For each element \(i\), the minimum number of operations required to make \(A_i\) and \(B_i\) equal is \(|A_i-B_i|\), and the answer is their sum \(\sum_{i=1}^{N}|A_i-B_i|\).
Discussion
The operation is “per operation, choose exactly one index \(i\) and change \(A_i\) or \(B_i\) by \(\pm 1\).”
In other words, the indices are completely independent (an operation changing index \(i\) does not affect elements at index \(j(\neq i)\)).
Therefore, the overall minimum number of operations is “the sum of the minimum number of operations required for each \(i\).”
Now, for a fixed \(i\), let us consider the minimum number of operations to make \(A_i=a\) and \(B_i=b\) equal.
- In one operation, the only thing we can do is move \(a\) or \(b\) by \(\pm 1\).
- Therefore, the difference \(|a-b|\) can be reduced by at most 1 per operation.
- On the other hand, for example, by applying \(+1\)/\(-1\) to \(a\) exactly \(|a-b|\) times in the direction toward \(b\), we can always make them equal.
Thus, the minimum number of operations is exactly \(|a-b|\).
Concrete Example
If \(A_i=3, B_i=10\), the difference is \(|3-10|=7\).
By increasing \(A_i\) seven times to make it \(10\), they become equal, so the minimum is 7 operations (alternatively, decreasing \(B_i\) seven times also works).
Summing this over all \(i\) gives the answer.
If you naively try to “simulate the sequence of operations and minimize,” a search would be required and this is not practical. However, in this problem, indices are independent, and the optimal solution for each index is immediately determined as \(|A_i-B_i|\), so it can be solved with a simple summation.
Algorithm
- Initialize \(ans=0\)
- For each \(i=1..N\), perform \(ans \leftarrow ans + |A_i-B_i|\)
- Output \(ans\)
Complexity
- Time complexity: \(O(N)\) (just looking at each element once)
- Space complexity: \(O(1)\) (no large additional space is needed beyond the input arrays)
Implementation Notes
In Python, you can simply sum up
abs(a-b).Since \(N\) can be up to \(2\times 10^5\), it is safe to use
sys.stdin.readlinefor input.The total can be as large as approximately \(N \cdot 2\times 10^9\), but since Python integers have arbitrary precision, there is no concern about overflow.
Source Code
import sys
def main():
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = 0
for a, b in zip(A, B):
ans += abs(a - b)
print(ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: