This observation shows that the an is minimal if and only if a1 is minimal, and is obtained by a1+∑i=1n−1di.
suppose two numbers ai,aj,i<j, we can either make a1←a1+2(ai−aj) or a1←a1−2(ai−aj)
To get a1←a1−2(ai−aj), we do (i,prefix)→(j,prefix). To get a1←a1+2(ai−aj), we do (i,suffix)→(i,prefix)→(j,prefix).
This means that we just need to minimize a1 by adding or subtracting (2n) pairs of 2(ai−aj), which is sufficient to use only (n−1) pairs, i.e. 2(ai+1−ai)
Suppose g=gcdi2∣ai+1−ai∣, this is equivalent to a1←a1modg. Be careful of g=0 case and g∣a1 case. Time complexity O(nlogV)
AC Code
AC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<bits/stdc++.h>
intmain(){ int n; std::cin >> n; std::vector<longlong> a(n), d; for (int i = 0; i < n; i++) { std::cin >> a[i]; if (i >= 1) d.push_back(std::abs(a[i - 1] - a[i])); }
auto f = 0ll; for (auto x : d) f = std::gcd(f, x * 2);
auto begin = f == 0 ? a[0] : (a[0] % f == 0 ? f : a[0] % f); std::cout << begin + std::accumulate(d.begin(), d.end(), 0ll) << "\n"; }