The 10th Blue Bridge Cup java-c group-arithmetic sequence

1. Problem description: The
mathematics teacher gave Xiao Ming a question about the sum of arithmetic series. But the careless Xiao Ming forgot part of the sequence, only the N integers in it. Now given these N integers, Xiao Ming wants to know how many items are in the shortest arithmetic sequence containing these N integers?
[Input format]
The first line of input contains an integer N. The second line contains N integers A1, A2,..., AN. (Note that A1 ∼ AN are not necessarily given in the order in the arithmetic sequence)
[Output format]
Output an integer to represent the answer.
[Sample input] 5 2 6 4 10 20
[Sample output] 10
[Sample description]
The shortest arithmetic sequence containing 2, 6, 4, 10, 20 is 2, 4, 6, 8, 10, 12 , 14, 16, 18, 20.
[Evaluation use case scale and convention]
For all evaluation use cases, 2≤ N ≤100000, 0≤ Ai ≤10^9.

2. Thinking analysis:

An easier way to think of is to sort these N integers first, and then use the list to record the difference between two adjacent elements in the loop after sorting, and then we need to choose the smallest difference from these differences (it must be The smallest difference can constitute an arithmetic sequence), and finally starting from this smallest difference, judge whether all elements in the difference list of two adjacent elements recorded before can be divisible by the current smallest difference, if it is found The element cannot be divisible by the current smallest difference, so the difference needs to be further reduced until a value that can be divisible by all the differences in the list is found. It is possible that the final tolerance is equal to 0, so we calculated the smallest tolerance at the beginning and found that it is 0, just output N directly, otherwise according to the formula an = a1 + (n-1) * d to solve for d , Mainly enumerate a process. Some real questions of the Blue Bridge Cup can be submitted on the c language website

3. The code is as follows:

import math
if __name__ == '__main__':
    # 首先需要求解出这个序列中最小的差值
    n = int(input())
    nums = list(map(int, input().split()))
    nums.sort()
    cha = list()
    for i in range(1, n):
        cha.append(nums[i] - nums[i - 1])
    min_cha = math.pow(10, 9) + 1
    for i in range(len(cha)):
        min_cha = min(min_cha, cha[i])
    if min_cha == 0: print(n)
    else:
        dengcha = 1
        for i in range(min_cha, 0, -1):
            f = 1
            for j in range(len(cha)):
                if cha[j] % i != 0:
                    f = 0
                    break
            if f:
                dengcha = min_cha
                break
        # 根据an与a1的关系可知
        print((nums[-1] - nums[0]) // dengcha + 1)

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/115033425