公式

A - 数値列の一致 / Matching Sequences 解説 by admin

DeepSeek V3

Overview

This problem asks for the minimum number of operations to make two numerical sequences A and B identical, where each operation increases or decreases an element by 1.

Analysis

For each index i, we need to close the gap between A_i and B_i. The key observation is that one operation can change a value in only one of the two sequences by 1. In other words, for each index i independently, we need exactly as many operations as the absolute difference between A_i and B_i. This is because the mismatch at each position can only be corrected by operations at that position, and there is no way to combine operations across different positions for greater efficiency.

Algorithm

For each index i, compute |A_i - B_i| and sum these values. This sum is the minimum number of operations. For example, if A_i = 3 and B_i = 5, then 2 operations are needed (either increase A_i twice, decrease B_i twice, or some combination of both), but in any case a total of 2 operations are required.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(N)\)

Implementation Notes

After reading the input, the problem can be solved by simply summing the absolute differences of each pair of elements. In Python, this can be written concisely using the built-in abs() function. Input is read efficiently using sys.stdin.read().

Source Code

def main():
    import sys
    data = sys.stdin.read().split()
    n = int(data[0])
    A = list(map(int, data[1:1+n]))
    B = list(map(int, data[1+n:1+2*n]))
    
    total_ops = 0
    for i in range(n):
        total_ops += abs(A[i] - B[i])
    
    print(total_ops)

if __name__ == "__main__":
    main()

This editorial was generated by deepseekv3.

投稿日時:
最終更新: