We need to understand the problem: There is a sequence a of length m, each element between 1 and n. We can perform at most one operation: choose two pages x and y (1 ≤ x, y ≤ n) and merge page x into y. This changes all occurrences of x in a to y. (If x=y, nothing changes). We want to minimize the sum of absolute differences between consecutive elements in the modified sequence: S = sum_{i=1}^{m-1} |a_i' - a_{i+1}'|.
We need to compute the minimal possible S after at most one such merge.
Observations:
We can choose any x (the page to be merged) and any y (target page). The operation is effectively: pick two distinct values (if x=y no effect) and replace all occurrences of x in the sequence with y. This changes only the values equal to x.
We need to find which merge reduces the total distance most.
Brute force over x and y would be O(n^2) too large (n up to 1e5). Need more clever.
Let's denote original sequence a. Compute original total T = sum_{i=1}^{m-1} |a_i - a_{i+1}|.
If we replace all x with y, only edges (i,i+1) where at least one endpoint equals x will change. Other edges remain unchanged.
Specifically, for each adjacent pair (a_i, a_{i+1}), the contribution to sum is |a_i - a_{i+1}|. After replacement, if we replace x by y, the new values are:
if a_i == x then a_i' = y else a_i; similarly for a_{i+1}. So the contribution becomes |b_i - b_{i+1}| where b_i = (a_i == x ? y : a_i). So the change Δ = new_sum - old_sum. We want to minimize new_sum = T + Δ, so we want Δ as low as possible (could be negative). For each candidate x, we need to find y that minimizes Δ.
We need to compute for each value x (1..n) the optimal y and Δ, then take min Δ. But note y can be any value from 1..n, possibly not equal to x. But if we set y = x, Δ=0. So we only care about y ≠ x that yields negative Δ.
Now, how to compute for a fixed x the best y efficiently? We need to consider all edges incident to x (i.e., pairs (i,i+1) where a_i = x or a_{i+1}=x). Let's list all such edges. For each edge, we have original values (u,v) with at least one equals x. After replacement, they become (u', v') where if u=x then u'=y else u; similarly for v.
Original contribution: d_orig = |u - v|.
New contribution: d_new = |u' - v'|.
We need to compute the total Δ_x(y) = sum over all such edges (d_new - d_orig). Note that edges not involving x remain unchanged, so they contribute 0 change.
Therefore, for each x, we have a set of edges where x appears. The number of such edges can be large, but total over all x is at most 2*(m-1) because each edge involves two values, so each edge contributes to at most two x's. So overall O(m) edges total.
For a given x, we have a list of edges. For each edge, there is a neighbor value v (the other page) if both ends are x? Actually, edges can be (x, x) as well. In that case original d_orig=0. After replacement, both become y (since both x's become y), so d_new = 0, so no change. So edges (x,x) can be ignored because they contribute 0 regardless of y.
So consider edges where one endpoint is x and the other is some value v ≠ x. There are two types: (x, v) with x < v or > v; but we can treat them similarly. For an edge (x, v) (with v ≠ x), original d_orig = |x - v|.
After replacement, the x becomes y, the v stays v (if v != x). So new contribution = |y - v|. So change = |y - v| - |x - v|.
Thus, for each such edge, we have a function of y: f(y) = |y - v| - |x - v|.
So Δ_x(y) = sum_{edges incident to x, v ≠ x} (|y - v| - |x - v|).
Since the constant term -|x - v| does not depend on y, we can define:
Δ_x(y) = C_x + sum_{edges} |y - v|, where C_x = - sum_{edges} |x - v| (constant independent of y). So minimizing Δ_x(y) is equivalent to minimizing S_x(y) = sum_{edges} |y - v| (over y in [1..n]), because constant doesn't affect optimal y. However, we must also consider edges where both ends are x? They yield 0 change regardless, so they can be ignored; indeed they would contribute constant 0 and also |y - y|? Actually if both are x, after replacement both become y, so new = |y-y|=0, original =0, so change=0, so they can be ignored. So we can safely ignore edges (x,x) because they add nothing to sum of |y-v|? Actually they would add |y - y| = 0, so they don't affect S_x(y). So ignoring is fine.
Thus, the problem reduces to: For each value x, we have a multiset of neighbor values v (the other page numbers) from incident edges where the other is not x. For each such x, we need to find y that minimizes the sum of absolute distances to these v values. That's classic: the optimal y is any median of the multiset of v values (if we minimize sum of absolute deviations). However, we are allowed to choose any y between 1 and n. But also note: if y is chosen not equal to any neighbor? The median minimizes sum of absolute distances; if the median is not integer? The v are integers, so median among integers; the minimizer is any median (if even number, any value between the two middle values). So we can take the median (lowest median is fine) and compute minimal sum.
Thus, for each x, the best y is the median of its incident neighbor values v (the multiset). However, we must also consider that y can be any integer in [1,n], but median may be out of that range? v are between 1..n, so median is also within that range. So fine.
But wait: we also need to consider the constant C_x. The total Δ_x(y_opt) = C_x + sum_{v} |y_opt - v|. And original T is known. So the new total = T + Δ.
But we must be careful: if we merge x to y, we change all occurrences of x to y. However, what about edges where both endpoints become y? For an edge (x, v) with v = x, we ignore. But also consider the possibility that after replacement, edges that originally did not involve x could become different if they involved y? Wait: The operation only changes occurrences of x to y. It does not change occurrences of any other page. However, if y is some other value, and originally there were edges between y and some other value, then after the merge, we are adding new occurrences of y (since some x become y). This could affect the sum? But note that the sum S is computed from the modified sequence a'. In edges that originally had endpoints (y, w) (with w not x) they remain (y, w) because y stays y and w unchanged. However, when we replace x with y, we might create new edges between y and some neighbor that was originally v, but that edge was already considered in the incident edges of x because that edge was (x, v). In the modified sequence, the edge becomes (y, v). That's accounted for in our Δ calculation: we replaced |x - v| with |y - v|. But also, what about edges between two x's? They become (y, y) and contribute 0 change, which is fine. But there is a subtlety: edges that originally were between y and some other value w (not x) could be affected because after replacing x with y, the number of occurrences of y increases. However, the values themselves in those edges are still y and w. The only thing that changes is the sequence of values, but the edges themselves: if there is a segment ... y ... w ... where the y is originally y, that stays the same. However, when we convert some x to y, we are inserting extra y's into the sequence, and the adjacency may change: but adjacency only involves consecutive positions. For each position i, a_i and a_{i+1}. When we change some a_i from x to y, the edges on both sides of that position change: (a_{i-1}, a_i) and (a_i, a_{i+1}). In our approach, we considered all edges where a_i = x or a_{i+1}=x. That's exactly those incident edges. But what about the edge (a_{i-1}, a_i) where a_{i-1} = y originally? That edge originally is (y, x) before change. After change it becomes (y, y). That's still an edge where one endpoint is x originally? Yes, it is an edge incident to x: (x, y) originally. We accounted for it as (x, v) with v = y. So after change, it's (y, y) => contribution 0. But we accounted for it as |y - y| - |x - y| = -|x - y|. That's correct. But does this edge originally exist? Yes, if there was an edge between y and x. But if there was no edge between y and x originally, then after converting x to y, we might create a new edge between y and y? Actually if we convert a single x that is adjacent to some other value w (not y), then after conversion we get edge (y, w). That's handled. But what about edges that were originally between two y's? They remain unchanged; those edges don't involve x, so they are not considered in Δ. That's fine because they are unchanged. However, there is a catch: The sum of contributions from edges not involving x is unchanged, that's true. But wait: What if we merge x to y, and y is some value that appears many times. The edges that originally involved y but not x remain as they are. However, the replacement also changes the edges that originally were (x, x) to (y, y). That's also considered in incident edges? Actually (x,x) edges are edges where both endpoints are x. They are incident to x (both endpoints) but we said they contribute 0 change regardless. So it's fine. So our Δ calculation seems correct.
Therefore, for each x, we need to:
-
Collect all neighbor values v from edges where the other endpoint is not x. For each occurrence of an edge (a_i, a_{i+1}) with a_i = x, a_{i+1} = v ≠ x, we add v to the multiset. Similarly for edges where a_{i+1} = x, a_i = v ≠ x, we add v. So each such edge contributes one v (the non-x value) to the multiset for x. But careful: if both endpoints are x, ignore. Also note: if an edge is (x, v) with v ≠ x, it appears once for x with neighbor v. So that's fine.
-
Compute the sum of absolute distances from x to all v: sum_abs_x = sum_{v} |x - v|. This is the total original contribution from incident edges (excluding (x,x) edges). Actually original contribution from incident edges to sum T includes all edges involving x. For an edge (x, v) original contribution is |x - v|. So sum_abs_x is part of T. But not all of T. But we need constant C_x = - sum_{v} |x - v|. So after we compute S_x(y) = sum_{v} |y - v|, we have Δ = S_x(y) - sum_{v} |x - v|.
Thus, for each x, we need to compute:
- cnt_x: number of incident edges with neighbor ≠ x (i.e., size of multiset)
- sum_abs_original = sum_{v} |x - v|
- The multiset of v's.
Then compute median m_x (or find best y) and compute sum_abs_new = sum_{v} |y_opt - v|. Then Δ_opt = sum_abs_new - sum_abs_original.
Then answer = T + min(Δ_opt over all x, and 0) (since we can choose not to merge, i.e., Δ=0). Actually at most one merge; so we can also not do any operation, giving total = T. So we take min(T, T + minΔ). But minΔ may be negative, so effectively answer = T + min(0, minΔ). But since we compute Δ for each x and we consider y possibly equal x? We can just compute Δ_opt for each x, which could be negative or positive; the best merge yields minimum total = T + min_x Δ_opt. But we should also consider the possibility that no operation is allowed? Problem says "she can apply the described operation at most once before the reading." So it's optional. So answer = min(T, T + min Δ). But since Δ for x where y=x is 0, min Δ will be ≤ 0. Actually if we consider y=x, Δ=0. So if we don't merge, we get 0. So min over all x and all y is at most 0. But we need to make sure we consider y=x as a candidate? Our approach of picking median may produce y possibly equal to x; but if the median equals x, then sum_abs_new = sum_abs_original, so Δ=0. So minΔ will be <=0. So answer = T + minΔ.
Thus the task reduces to: compute T originally; for each value x, collect neighbor multiset; compute best reduction possible by merging x to some y.
Now we need to compute efficiently for all x, given the neighbor multisets. Since total number of neighbor entries across all x is O(m) (each edge contributes at most two entries: for each endpoint if the other is different). Actually each edge (a_i, a_{i+1}) with u != v contributes one entry to multiset of u (neighbor v) and one entry to multiset of v (neighbor u). If u == v, it contributes nothing. So total entries E ≤ 2(m-1). So we can process each x individually by gathering its list of neighbors.
For each x with list L_x (size s_x), we need to compute:
-
sum_abs_original = sum_{v in L_x} |x - v|.
-
The y that minimizes sum_{v in L_x} |y - v|. That's median: let sorted L_x. Let s = len(L_x). If s == 0, then no incident edges? Then merging x to any y won't affect total? Actually if x never appears in sequence? But could appear? a_i could be any from 1..n; but if x doesn't appear in sequence, then merging it does nothing because no occurrence to replace. So Δ=0. So we can ignore x with no occurrences or no incident edges? However, x might appear isolated? If x appears only as isolated occurrences? Actually even if x appears but never adjacent to a different value? For example, if all occurrences of x are isolated? But adjacency always exists between consecutive elements; if sequence is length m, there are m-1 edges. If x appears in positions, the edges incident to x are those where either a_i = x and a_{i+1} = something, or a_{i+1}=x and a_i = something. So if x appears only at positions that are not adjacent to any other x? Actually if there is only one occurrence of x, then it has two incident edges (unless at ends). At start: only right edge; at end: only left edge. So there will be neighbors unless the sequence length is 1? But m can be 1? m can be 1 (since 1 ≤ m ≤ 1e5). If m=1, then there are no edges; T=0; any merge doesn't change anything; answer 0. So handle m=1 separately. But in general for m>=2, x may have incident edges if it appears. But if x appears but all its incident edges are with x (i.e., it is surrounded by x's), then all neighbor values are also x; but then those edges are (x,x) which we ignore because v ≠ x. So L_x would be empty if every incident edge has the other also equal to x. That can happen if x appears in blocks, and each occurrence of x that is not at the boundaries of the block will have both neighbors x, so no edges to other values. However, at the boundaries of the block, there will be an edge between x and a different value, unless the block is at the start or end? Actually at block boundaries, the edge between the last x and the next different value is (x, v). So that contributes v to L_x. So x will have some neighbors unless the entire sequence consists solely of x's. If all a_i = x, then there are edges (x,x) only; L_x empty. Merging x to any y would change all x's to y, and then all edges become (y,y) so T remains 0. So Δ=0. So for L_x empty, we can treat Δ_opt = 0 (since no change or change doesn't affect sum? Actually if we merge x to y, all x become y. The edges originally were (x,x) contributed 0; after merging they become (y,y) also 0, so total unchanged. So Δ=0. So we can skip those.
Thus, for each x with non-empty L_x, we need to compute median and sum of absolute deviations from median.
But we need to compute sum_abs_new efficiently for the median. Since we have the list L_x, we can sort it. But if we sort individually for each x, total sorting time could be O(sum s_x log s_x). However, total sum of s_x is O(m). But if we sort each list individually, the sum of s_x log s_x might be larger than O(m log m) in worst case? Let's consider: if one x has s_x = O(m) (if a value appears many times and is adjacent to many different neighbors), then sorting that one list costs O(m log m). That's okay overall since m ≤ 1e5. The total could be O(m log m) because each edge contributes to at most two lists, and sorting each list individually: The sum over x of s_x log s_x is maximized when the distribution is as skewed as possible? Actually we can bound: sum s_x = 2E ≤ 2m. And we know that sum s_x log s_x ≤ (sum s_x) * log(max s_x) (since log is concave? Actually it's convex, so by Jensen, sum f(s_x) is maximized when the distribution is as unequal as possible? For convex functions, the sum given fixed total sum is maximized when as many as possible are as large as possible. The worst case is one list has all entries, say s_max = 2E, others 0. Then sum s_x log s_x = (2E) log (2E) ≤ O(m log m). So it's O(m log m). So it's fine.
Thus, we can do:
-
Read n, m.
-
Read array a of length m.
-
Compute T = sum |a[i] - a[i+1]| for i=1 to m-1.
-
Build adjacency lists: For each i from 0 to m-2:
u = a[i], v = a[i+1]
if u == v: continue (no effect)
else:
add v to list of u
add u to list of v
But careful: We need to record each neighbor occurrence separately because edges may repeat. So it's a multiset. So we just push values into a vector per x.
Alternatively, we could store sorted lists later.
- For each x from 1 to n:
if list L_x is empty: continue (Δ=0, but we might still consider? Not needed as minΔ won't be positive)
else:
sort L_x.
compute sum_abs_original = sum |x - v| for v in L_x. (We can compute while iterating before sorting, but need values; we can compute after sorting, doesn't matter.)
Find median: let s = len(L_x). Let median candidates: if s odd, median = L_x[s//2] (0-indexed). If s even, any value between L_x[s/2 -1] and L_x[s/2] inclusive minimizes sum. Usually we can take lower median or upper median; but we need to compute minimal sum. To compute minimal sum, we could compute sum of absolute deviations from median, but since we have sorted list, we can compute prefix sums to quickly compute sum of |y - v| for any y, but we only need for the median. However, note: For even length, any y between the two middle values gives same minimal sum? Actually the sum of absolute deviations is piecewise linear with slope changing at each data point. For even number of points, the set of minimizers is any point between the two middle points (including them). The minimal sum is achieved for any y in [mid1, mid2]. The minimal sum is constant across that interval. So we can compute sum using either mid1 or mid2. So we can take y = L_x[s//2] (if 0-indexed, that's the floor median) and compute sum_abs_new = sum |y - v|. That yields the minimum? For even count, picking the lower median gives sum that is not necessarily equal to the true minimum? Let's verify: Suppose data points: 1, 10. The sum of absolute deviations is |y-1|+|y-10|. The minimum is achieved for any y in [1,10] and minimal value = 9. If we pick y=1, sum = 0+9=9, correct. y=10 gives 9, correct. So picking either endpoint yields the same sum? Actually y=1 gives 0+9=9, y=10 gives 9+0=9. So yes. If we pick a point outside [1,10], sum >9. So any point between gives 9. So indeed picking either median works. So we can take median as L_x[s//2] (0-indexed) for simplicity.
But we must be careful: The sum of absolute deviations from the lower median equals the sum from the upper median? Not exactly? Actually if you have points a≤b, then for any y ∈ [a,b], sum = (y-a)+(b-y) = b-a, constant. So yes, it's constant. So picking either gives same sum. So fine.
Thus, compute sum_abs_new = sum |med - v|. This can be computed by iterating the sorted list, but we can also compute using prefix sums to avoid O(s) per x? But total O(s_x) across all x is O(m). So we can just loop over L_x after sorting and compute both sum_abs_original and sum_abs_new in one pass.
However, we need sum_abs_original: sum |x - v|. Could compute while building lists, but that also requires sorting? Actually we could compute sum_abs_original by summing over v: |x - v|. That can be computed before sorting. Since we have the vector, we can compute sum_abs_original by iterating the unsorted vector; no need to sort for that. But we also need sorted list to compute median and sum_abs_new. So we can compute sum_abs_original first, then sort, then compute median and sum_abs_new by iterating again. That's O(s_x log s_x + s_x). Acceptable.
Alternatively, we could compute all needed in one pass after sorting: after sorting, we can compute sum_abs_new, and also we need sum_abs_original? We could compute sum_abs_original from unsorted values. That's fine.
Implementation steps:
-
Input.
-
if m == 1: output 0 (since no page turns). Return.
-
Compute T.
-
Create vector<vector> neighbors(n+1); (1-indexed)
-
For i from 0 to m-2:
u = a[i], v = a[i+1];
if u != v:
neighbors[u].push_back(v);
neighbors[v].push_back(u);
-
Initialize bestDelta = 0 (since we can choose no merge). Actually we will compute minDelta, which may be negative. We'll track minDelta = 0 initially? But we need to consider merges. So set minDelta = 0 (i.e., no merge). Then for each x with non-empty neighbors:
compute sum_abs_original = sum_{v in neighbors[x]} |x - v| (could be computed as long long)
sort neighbors[x]
s = size.
med = neighbors[x][s/2]; // integer division flooring
compute sum_abs_new = 0;
for each v in neighbors[x]: sum_abs_new += abs(med - v);
delta = sum_abs_new - sum_abs_original;
if delta < minDelta: minDelta = delta;
But careful: For x with neighbors but we might also consider y not exactly median? The median as we defined gives minimal sum_abs_new. However, is it possible that y (the target page) must be from 1..n but median is within that range. So yes, median works.
But there is a nuance: The operation merges page x to page y. After merging, all occurrences of x become y. But what if y equals some other value that also appears? That's fine. But is there any restriction that merging could cause some page to be merged into itself? Not relevant.
Now, are there any edge cases where the best y is not a median due to the fact that we change only occurrences of x, but not other pages, and there might be some interaction through edges that originally involved y? Wait, we earlier argued that edges not involving x remain unchanged. However, consider an edge (y, w) where w is not x. After merging x to y, there will be more occurrences of y. But the edges that originally were (y, w) remain as (y, w). But there might be new edges involving y that were originally (x, w) and become (y, w). Those are accounted for as edges incident to x. So no double counting.
Thus, the optimization per x is indeed to minimize sum of |y - v| over neighbors v. So median is optimal.
But is there any situation where we might want to merge x to a value y that is not among the neighbor list, but maybe because it also reduces the cost from edges that were originally (x, x)? Those edges contribute 0 anyway. So no.
So the solution seems correct.
Now, let's test with given examples.
Example1:
n=4, m=6, a = [1,2,3,4,3,2]
Compute T:
|1-2|=1, |2-3|=1, |3-4|=1, |4-3|=1, |3-2|=1 => T=5? But sample output says after merging 4 to 3 total = 3. Original T? Let's compute original total correctly: The sum is 1+1+1+1+1 = 5. After merging 4->3, sequence becomes 1,2,3,3,3,2: sums: |1-2|=1, |2-3|=1, |3-3|=0, |3-3|=0, |3-2|=1 => total=3. So reduction of 2.
Now our algorithm:
Edges (i,i+1):
(1,2): u=1,v=2 -> neighbors[1] add 2; neighbors[2] add 1.
(2,3): -> neighbors[2] add 3; neighbors[3] add 2.
(3,4): -> neighbors[3] add 4; neighbors[4] add 3.
(4,3): -> neighbors[4] add 3; neighbors[3] add 4. (So 3 gets two 4's? Actually careful: (4,3) gives neighbors[4] add 3, neighbors[3] add 4. So 3 gets another 4.)
(3,2): -> neighbors[3] add 2; neighbors[2] add 3.
Now for each x:
x=1: neighbors = [2]. sum_abs_original = |1-2|=1. sorted [2], med=2. sum_abs_new = |2-2|=0. delta = -1. So possible reduction 1 by merging 1 to 2? But is that valid? If we merge 1->2, sequence becomes all 2's? Actually original: 1,2,3,4,3,2 -> merge 1 to 2: becomes 2,2,3,4,3,2. Then T: |2-2|=0, |2-3|=1, |3-4|=1, |4-3|=1, |3-2|=1 => total=4. So reduction 1. So delta=-1 indeed. But the best is -2 from merging 4->3.
x=2: neighbors = [1,3,3]? Let's list: from edges (1,2): 2 gets neighbor 1; (2,3): neighbor 3; (3,2): neighbor 3. So neighbors[2] = [1,3,3]. sum_abs_original = |2-1| + |2-3| + |2-3| = 1+1+1=3. sorted [1,3,3], med = index1 (0-indexed 1) = 3. sum_abs_new = |3-1|+|3-3|+|3-3| = 2+0+0=2. delta = -1.
x=3: neighbors = [2,4,4,2]? Actually from (2,3): add 2; (3,4): add 4; (4,3): add 4; (3,2): add 2. So neighbors[3] = [2,4,4,2] -> [2,2,4,4]. sum_abs_original = |3-2|2 + |3-4|2 = 12 + 12 = 4. sorted, med index 2? size 4, s/2 =2, med = neighbors[2] = 4? Actually sorted [2,2,4,4], index 2 (0-indexed) is 4. sum_abs_new = |4-2|+|4-2|+|4-4|+|4-4| = 2+2+0+0=4. delta=0. Alternatively, if we take median 2? For even length, any between 2 and 4 inclusive yields minimal sum. Check y=2: sum_new = |2-2|+|2-2|+|2-4|+|2-4|=0+0+2+2=4, same. y=3: sum = 1+1+1+1=4? Actually |3-2|+|3-2|+|3-4|+|3-4| =1+1+1+1=4. So minimal sum is 4, same as sum_abs_original? That gives delta=0. So merging 3 to something yields no improvement.
x=4: neighbors = [3,3] from edges (3,4) and (4,3) actually careful: (3,4) gives neighbor 3 for 4; (4,3) gives neighbor 3 for 4. So neighbors[4]=[3,3]. sum_abs_original = |4-3|*2 = 2. sorted [3,3], med = neighbors[1]? size=2, s/2=1, index1=3. sum_abs_new = |3-3|+|3-3| = 0. delta = -2. So minDelta = -2. Then answer = T + (-2) = 5-2=3. matches sample.
So algorithm works.
Second sample:
n=10, m=5, a = [9,4,3,8,8]
Edges:
(9,4): add 4 to 9, add 9 to 4.
(4,3): add 3 to 4, add 4 to 3.
(3,8): add 8 to 3, add 3 to 8.
(8,8): equal, ignore.
Now compute T: |9-4|=5, |4-3|=1, |3-8|=5, |8-8|=0 => total 11? But sample output says 6 after merging 9 to 4. Wait sample says "Output 6". Let's verify original total? Actually compute: 9-4=5, 4-3=1, 3-8=5, sum = 11. After merging 9->4, sequence becomes 4,4,3,8,8. Sum: |4-4|=0, |4-3|=1, |3-8|=5, |8-8|=0 => total 6. So reduction 5. So original T is 11. Our T calculation: 5+1+5+0=11 correct.
Now compute per x:
x=9: neighbors = [4] only. sum_abs_orig = |9-4| =5. med=4, sum_new=0 => delta=-5. So minDelta=-5. Answer=11-5=6. Good.
So algorithm yields correct.
Thus, solution seems straightforward.
Potential pitfalls:
- Use 64-bit integers (long long) for sums because answer can exceed 32-bit.
- m=1 case: T=0, no edges, so any merge does nothing, answer 0.
- For x with empty neighbors: delta=0, skip.
- Need to be careful that sum_abs_original may be computed from unsorted list but we need to ensure we use same set of neighbors as the ones used for median. That set is all neighbors where the other endpoint is not x. But we included all edges where u!=v and x is one endpoint. That's correct. For edges where both endpoints are x, we ignored, but they contribute 0 to both original and new sums. So they don't affect delta.
But is there any scenario where merging x to y could affect edges where both endpoints were originally x? They become (y,y) and still 0. So no.
Edge case: What if after merging, some edges that were originally between y and some other value w get new contributions? Not changed. But wait, what about edges where originally both endpoints are y? unchanged.
Thus algorithm is correct.
But we need to verify the statement: "If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place." So merging x to y changes x to y. So all occurrences of x become y. The other pages remain same.
Hence the reasoning holds.
Now, confirm that our neighbor collection exactly corresponds to edges that will change. For each occurrence of x at position i (except possibly ends), we have two incident edges: left edge (a_{i-1}, a_i) and right edge (a_i, a_{i+1}). But in our neighbor list, we added v from each edge (a_i, a_{i+1}) where a_i = x, v = a_{i+1}; and from edge (a_{i-1}, a_i) we added v = a_{i-1} when processing that edge? Actually we iterate over edges (i,i+1). For each edge (u, v) with u != v, we add v to neighbors[u] and u to neighbors[v]. This includes both left and right contributions for each occurrence, except for edges at boundaries. At start, a_0 has only right edge; that edge is included when i=0 (a_0, a_1). So neighbor for a_0 gets v=a_1. For a_1, left edge is also from the same edge, but we add u to neighbors[v] (i.e., a_0 to neighbors[a_1])? Actually for edge (a_0,a_1), we add v to neighbors[u] and u to neighbors[v]. So for a_1, we add a_0 to its neighbor list, which is exactly the left neighbor for a_1. So this works. For last element a_{m-1}, the only edge is (a_{m-2}, a_{m-1}) which is processed, so a_{m-1} gets neighbor a_{m-2}. So yes, each occurrence's incident edges are captured.
Thus neighbors list for x contains all values v such that there is an edge between x and v (with v possibly equal to x? but we excluded u=v so no self edges). So correct.
Now, complexity: O(m) memory, O(m log m) time due to sorting.
Implementation details:
-
Use vector<vector> adj(n+1).
-
Compute T as long long.
-
Loop i=0..m-2:
u=a[i], v=a[i+1];
if u==v: continue;
adj[u].push_back(v);
adj[v].push_back(u);
-
For each x in 1..n:
if adj[x].empty(): continue;
// compute sum_abs_original
long long sum_orig = 0;
for(int v: adj[x]) sum_orig += abs(x - v); // careful: abs may be int; use casting.
sort(adj[x].begin(), adj[x].end());
int sz = adj[x].size();
int med = adj[x][sz/2];
long long sum_new = 0;
for(int v: adj[x]) sum_new += abs(med - v);
long long delta = sum_new - sum_orig;
if(delta < bestDelta) bestDelta = delta;
-
Answer = T + bestDelta; (since bestDelta is negative or zero). Print answer.
But note: T and sums must be 64-bit. Use long long.
Now, double-check with potential tricky cases:
Case: m=2, a=[1,2]
Edges: (1,2). T=1.
adj[1]=[2], sum_orig=|1-2|=1, sorted [2], med=2, sum_new=0, delta=-1 => bestDelta=-1, answer=0. Is that correct? Merge 1 to 2: sequence becomes [2,2], sum=0. So yes.
If merge 2 to 1: adj[2]=[1], sum_orig=|2-1|=1, med=1, sum_new=0, delta=-1, answer=0. So both yields 0.
Case: m=3, a=[1,2,1]
Edges: (1,2), (2,1). T = |1-2| + |2-1| = 1+1=2.
adj[1]: neighbors: from (1,2) add 2; from (2,1) add 2? Actually edge (2,1) gives neighbors[1] add 2? Wait edge (2,1) with u=2,v=1: we add v to neighbors[u] (so neighbors[2] add 1) and u to neighbors[v] (so neighbors[1] add 2). So neighbors[1] gets 2 from both edges? Actually (1,2): adds 2 to neighbors[1] and 1 to neighbors[2]. (2,1): adds 1 to neighbors[2] and 2 to neighbors[1]. So neighbors[1] = [2,2]; neighbors[2] = [1,1].
Now for x=1: sum_orig = |1-2|+|1-2| = 2. sorted [2,2], med=2, sum_new=0, delta=-2. So merging 1->2 yields total 0? Let's check: Merge 1 to 2: sequence becomes [2,2,2], sum = 0. So T+(-2)=0, correct.
For x=2: sum_orig = |2-1|+|2-1| = 2. med=1, sum_new=0, delta=-2. So also 0.
Thus answer 0.
Case: a=[1,1,2,2]
Edges: (1,1) ignore; (1,2) from index1? Actually indices: a0=1,a1=1,a2=2,a3=2.
Edges: (1,1) ignore; (1,2) between a1 and a2: u=1,v=2 -> adj[1] add 2, adj[2] add 1; (2,2) ignore.
T = |1-1|+|1-2|+|2-2| = 0+1+0=1.
Now neighbors: x=1: [2]; x=2: [1].
For x=1: sum_orig =1, med=2, sum_new=0, delta=-1 => total 0.
For x=2: sum_orig=1, med=1, sum_new=0, delta=-1 => total 0.
Thus answer 0.
Case: a=[1,3,2]
Edges: (1,3), (3,2). T = |1-3|+|3-2| = 2+1=3.
adj[1]: [3]; adj[3]: [1,2]; adj[2]: [3].
x=1: sum_orig=2, med=3, sum_new=0, delta=-2 -> total 1? Actually 3-2=1. Check merging 1->3: sequence [3,3,2], sum = |3-3|+|3-2| = 0+1=1. Good.
x=3: neighbors [1,2], sum_orig = |3-1|+|3-2| = 2+1=3. sorted [1,2], med = (size2) index1? sz/2=1 -> med=2? Actually sorted [1,2], med = adj[3][1] = 2. sum_new = |2-1|+|2-2| = 1+0=1, delta = -2. So merging 3->2 yields sequence [1,2,2]? Wait merging 3 to 2: original [1,3,2] -> becomes [1,2,2], sum = |1-2|+|2-2| = 1+0=1. So total 1. So best delta = -2, answer=1.
x=2: sum_orig = |2-3|=1, med=3, sum_new=0, delta=-1 -> total=2. So min delta = -2.
Thus answer 1.
Now, what about the possibility that we could merge x to y where y is not a median but gives better overall because of constant? No, because Δ depends only on sum of |y-v|, which is minimized at median.
Thus algorithm seems solid.
But we must consider that y can be any integer from 1 to n, but the median may be a value that is not in the neighbor list? Actually median of a set of integers is always one of them or between two of them. The set of v values is from 1..n, so median is within range.
Now, the problem states: "If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n)". So both x and y must be pages from 1 to n, but note that after merging, the notebook still has pages from 1 to n? It says "merge two pages" but doesn't say that pages disappear; it says she copies information from x to y, so page x still exists? Actually the wording: "she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y." It doesn't say she removes page x, only that information is copied, and references to x become y. So x still exists but no longer used? Actually the sequence a values are changed to y. So it's essentially a relabeling. So x can be any from 1..n, y can be any from 1..n. So our approach is fine.
Now, confirm that we haven't missed any possible improvement from merging a page that appears only in edges where both endpoints are same? As discussed, no.
Also, check if there's any scenario where merging x to y could increase the number of pages turned for edges that originally didn't involve x, but involve y? For example, suppose we merge x to y and originally there are many edges (y, w) that have small differences. After merging, we will have more occurrences of y, but the edges (y, w) remain unchanged; the new edges (y, w) from converted x also contribute |y-w|. But that's exactly accounted in sum over v for x. So no extra effect.
Thus correct.
Now, implement.
Potential improvements: Instead of sorting each list, we could compute median using nth_element for O(s) average, but sorting is simpler and fine.
Edge case: large n up to 1e5 but many pages unused; we still allocate vector of size n+1.
Memory: adjacency list with total up to 2e5 ints -> ~0.8 MB, fine.
Now, let's test with custom cases.
Case: all values same, e.g., n=5, m=10, a all 3.
T = 0.
adj all empty => bestDelta=0 => answer 0.
Case: alternating: 1,2,1,2,... length m even.
Say m=4: 1,2,1,2.
Edges: (1,2),(2,1),(1,2). T=1+1+1=3? Actually |1-2|=1,|2-1|=1,|1-2|=1 => 3.
adj[1]: from (1,2) add 2; (2,1) add 2? Actually (2,1) adds 2 to neighbors[1]; (1,2) again? there are two (1,2) edges: positions (0,1) and (2,3). So neighbors[1] gets two 2's. So [2,2]. sum_orig=2, med=2, sum_new=0, delta=-2 => total=1. Check: merge 1->2: sequence [2,2,2,2] sum=0? Actually after merge all become 2: [2,2,2,2] sum=0. But delta -2 would give 3-2=1, not 0. Wait compute: T=3, delta from x=1: sum_orig= |1-2|+|1-2|=2, sum_new=0, delta=-2 => new total 1. But we can also merge 2->1: neighbors[2] = [1,1]? Actually edges: (1,2) gives 1 to 2; (2,1) gives 1 to 2; (1,2) gives 1 to 2. So neighbors[2] = [1,1,1]? Actually there are three edges? Let's list: indices: i0-1: (1,2) -> add 1 to neighbors[2]; i1-2: (2,1) -> add 1 to neighbors[2]; i2-3: (1,2) -> add 1 to neighbors[2]. So three 1's. sum_orig = |2-1|*3 = 3; med=1, sum_new=0, delta=-3 => new total 0. So best delta = -3, answer 0. So we missed merging 2->1 because we only considered x=1 and got -2, but x=2 gave -3. So minDelta = -3. Our algorithm will compute for x=2 as well, so that's fine. So answer = 0.
Thus both considered.
Now, consider case where median is not an integer? v are integers, median is integer if odd count; for even, we pick any integer between the two medians. The sum is constant across that interval, but our algorithm picks the lower median? Actually we pick med = adj[x][sz/2] which for even sz picks the element at index sz/2 (0-indexed). For sz=2, indices 0,1; sz/2=1 => picks the second element. That's the upper median. That's fine because sum is constant. For sz=4, indices 0,1,2,3; sz/2=2 => picks third element (upper median). So we are using upper median. Could there be a scenario where the optimal y is not equal to that median because y must be integer and the interval [mid1, mid2] contains integers? If both are integers, any integer between works. However, if the two medians are, say, 5 and 7, the interval [5,7] includes 6. 6 might give sum less? Let's compute: points: 5 and 7. The sum |y-5|+|y-7| = (y-5)+(7-y)=2 for any y in [5,7] (constant 2). So for y=6, sum=1+1=2, same. So constant. So any integer yields same sum. So median works.
Thus picking any median works.
Now, we should also consider the possibility that after merging, the total could become larger than original? That would not be used because we can choose not to merge. So we take min.
Now, potential issue: When we compute sum_abs_original, we sum over neighbors[x] which includes each edge incident to x exactly once. However, is the original contribution to T from edges incident to x exactly sum_{v} |x - v|? Let's verify: For each edge (x, v) with x != v, the contribution to T is |x - v|. But note: each edge (x, v) is counted once in neighbors[x] as v. But is there any edge (x, v) that appears multiple times? If there are multiple occurrences of the same edge (i.e., two consecutive positions with same pair (x,v) at different places), then neighbors[x] will contain v multiple times (once per occurrence). So sum_{v} |x - v| over the multiset will indeed sum the contributions from each occurrence. That matches because the total T is sum over all edges, each edge's contribution included. So that's correct.
Now, we must ensure we don't double-count edges: For each edge (x, v) with x != v, we add v to neighbors[x] and x to neighbors[v]. So each edge appears as one entry in each list. So sum_{v in neighbors[x]} |x - v| equals the sum of contributions of all edges where x is one endpoint. So that's correct.
Thus algorithm is sound.
Now, some optimization: we could compute sum_abs_original and also compute total sum of neighbors to compute median quickly. But sorting is fine.
Potential pitfalls with large data: Use long long for all sums. In C++, abs for int returns int; but it's okay as long as we cast to long long. We can store sums in long long.
Implementation steps in code:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> a(m);
for (int i = 0; i < m; ++i) cin >> a[i];
if (m == 1) {
cout << 0 << '\n';
return 0;
}
ll T = 0;
vector<vector<int>> adj(n+1);
for (int i = 0; i < m-1; ++i) {
int u = a[i], v = a[i+1];
T += abs(u - v);
if (u != v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
}
ll bestDelta = 0; // if we do nothing
for (int x = 1; x <= n; ++x) {
if (adj[x].empty()) continue;
ll sum_orig = 0;
for (int v : adj[x]) sum_orig += abs(x - v);
sort(adj[x].begin(), adj[x].end());
int sz = adj[x].size();
int med = adj[x][sz / 2];
ll sum_new = 0;
for (int v : adj[x]) sum_new += abs(med - v);
ll delta = sum_new - sum_orig;
if (delta < bestDelta) bestDelta = delta;
}
ll ans = T + bestDelta;
cout << ans << '\n';
return 0;
}
But wait: we used T computed as sum of |u-v| for all edges. However, in the loop we added to T each edge, including those with u=v. But for u=v, |u-v|=0, so it's fine. So T correct.
Now, consider that bestDelta could be positive? For some x, merging might increase sum? That could happen if the median sum is greater than original? Actually original sum is sum |x - v|. Since we are minimizing sum |y - v|, the minimum is at most sum |x - v| (since we can set y=x). So delta <= 0. So bestDelta will be <=0. So it's fine to initialize bestDelta=0.
But let's double-check: For x with neighbors, we compute delta = sum_new - sum_orig. Since sum_new is minimal over y, and y=x is a candidate (though maybe not exactly considered if we restrict to median? However, the median may equal x. If not, but we could still consider y=x. The minimal sum is less than or equal to sum at y=x. So sum_new <= sum_orig. So delta <= 0. So bestDelta will be non-positive. So initializing to 0 is fine.
But careful: For x with empty neighbors, we skip; merging x won't change anything, delta=0. So bestDelta remains 0 if all deltas are zero or positive? But as argued, delta never positive, so bestDelta will be 0 or negative.
Now, test with sample2: we got bestDelta=-5, T=11, ans=6.
Edge case: m=2, a=[1,2] -> T=1, bestDelta=-1, ans=0. Good.
Now, think about potential overflow: T up to? m <= 1e5, each |a_i - a_{i+1}| <= n-1 <= 1e5, so max T ~ 1e5 * 1e5 = 1e10, which fits in 64-bit ( < 2^63). Sum_orig similarly is sum over incident edges for each x, but overall not needed; but we use long long.
Now, we should test with a larger random case to sanity-check.
But before finalizing, there might be a nuance: When we merge x to y, we change all occurrences of x to y. However, in our neighbor list for x, we considered edges (x, v) and computed new contribution as |y - v|. But what about edges that originally were (x, v) but after merging, v might also be changed if v == x? That's not considered because v != x. So that's fine. But consider an edge (x, v) where v is also merged? But we only perform one merge, so v is not merged (unless v == x, but that's excluded). So no.
Another nuance: If we merge x to y, and y is also a neighbor of x (i.e., there exists edge (x, y) originally), then after merging, some of those edges become (y, y) and others become (y, y) if both endpoints x? Actually if we had an edge (x, y) originally, then after merging, the x becomes y, so the edge becomes (y, y). That's accounted for in our calculation: original edge contributed |x-y|; new contributes 0. In our neighbor list, that edge contributed v = y to the list for x; our formula gave new contribution = |y - y| = 0; so change = -|x-y|. So correct. But note: In the neighbor list for y, we also have an entry for that edge (since we added x to neighbors[y]). However, after merging x to y, we are not changing the occurrences of y, so edges where y is the other endpoint? Wait, that edge originally (x, y) is also in neighbors[y] with v = x. After merging x to y, do we need to adjust the contribution from that edge from the perspective of y? Actually the edge is the same edge. But we are computing Δ only from the perspective of x changes; but that edge appears in both lists? In our Δ calculation for merging x to y, we considered edges incident to x. The edge (x,y) is incident to x, so it's included in Δ_x. But what about the same edge from the perspective of y? In the total sum T, each edge is counted once. When we compute the change, we should account for that edge only once. By considering all edges incident to x, we have accounted for that edge exactly once (since we include it when one endpoint is x). The other endpoint being y does not need separate consideration because we are not modifying y. So the Δ we compute is correct. However, note that in our neighbor list for y, we have that edge too. But we are not merging y, so we don't consider it. So that's fine.
Thus algorithm seems correct.
Now, time to consider if there is any scenario where merging x to y could cause some edges that originally were not incident to x to become affected? For example, consider the sequence: ... y ... x ... y ... After merging x to y, we may have two y's that were originally separated by x become adjacent? Wait, adjacency is only between consecutive positions. If we have positions: i: y, i+1: x, i+2: y. Initially edges: (y, x) and (x, y). After merging x to y, the sequence becomes y, y, y. The edges become (y, y) and (y, y). So both edges change. In our method, both edges are incident to x (since x appears in both edges). So we account for them. So no new adjacency beyond those edges.
Thus correct.
One more nuance: The original T includes contributions from all edges. In our Δ computation for merging x, we sum over edges incident to x the change. However, note that if there are multiple edges between the same two values, they are all included as separate entries. So good.
Now, we should ensure we are not double-counting change for an edge (x, v) where both x and v are the same after merging? No.
Hence solution ready.
But the problem may have some tricky subtlety: The target y can be any page from 1..n. However, when we compute median for x's neighbors, that median might be x itself. In that case delta=0. But it's possible that choosing a y that is not the median but something else might give a delta < 0 if we also consider the effect on edges that originally involved y? No, as argued they are not changed.
But there's one more thing: What about edges between two different pages that both become the same after merging? For example, merging x to y could cause new edges between y and some other value w that originally existed as (x,w) but also there may already be edges (y,w). Both will contribute |y-w|. But that's fine because they are separate edges.
So answer is correct.
Now, double-check with a more complex case to ensure median indeed gives optimal. Suppose neighbors of x: [1, 100]. sum_orig = |x-1|+|x-100|. The best y to minimize sum |y-1|+|y-100| is any y in [1,100]. The sum is constant = 99. So if x is e.g., 50, sum_orig = 49+50=99, delta=0. If x=200, sum_orig =199+100=299, med=100? Actually neighbors [1,100]; med = 100 (since sz=2, index1=100). sum_new = |100-1|+|100-100| = 99, delta = -200. So merging x=200 to 100 yields reduction 200. That makes sense.
Now, think about potential corner: When x has many neighbors, median might be between two values but we choose the upper median; it's fine.
Thus solution is straightforward.
Now, we might want to further optimize by not sorting all lists but using quickselect to find median and also compute sums of left and right parts. However, sorting is simpler.
Given constraints m up to 1e5, sorting each list individually sum to O(m log m), which is fine.
But we should be careful with memory: we used adjacency list as vector<vector>. Each neighbor is stored twice. That's fine.
One nuance: The problem statement says n up to 1e5, m up to 1e5. So n could be larger than m; many pages unused. That's fine.
Now, test on random small cases by brute force to verify.
We could write a small test in mind.
Consider n=3, m=4, a=[1,2,3,2].
Compute T: |1-2|=1, |2-3|=1, |3-2|=1 => T=3.
Edges: (1,2): adj[1]=[2]; adj[2]=[1]
(2,3): adj[2] add 3; adj[3] add 2
(3,2): adj[3] add 2; adj[2] add 3 (so adj[2] gets another 3? Actually careful: (3,2) adds 2 to adj[3] and 3 to adj[2]. So adj[2] now has [1,3,3]? Wait from (1,2): adj[2] gets 1. from (2,3): adj[2] gets 3. from (3,2): adj[2] gets 3. So adj[2]=[1,3,3].
adj[1]=[2]
adj[3]=[2,2]
Now compute:
x=1: sum_orig=|1-2|=1; med=2; sum_new=0; delta=-1 -> new total 2 (merge 1->2: seq [2,2,3,2] sum=|2-2|+|2-3|+|3-2|=0+1+1=2)
x=2: sum_orig=|2-1|+|2-3|+|2-3|=1+1+1=3; sorted [1,3,3]; med=3; sum_new=|3-1|+|3-3|+|3-3|=2+0+0=2; delta=-1 -> new total 2 (merge 2->3: seq [1,3,3,3] sum=|1-3|+|3-3|+|3-3|=2+0+0=2)
x=3: sum_orig=|3-2|+|3-2|=1+1=2; sorted [2,2]; med=2; sum_new=0; delta=-2 -> new total 1 (merge 3->2: seq [1,2,2,2] sum=|1-2|+|2-2|+|2-2|=1+0+0=1)
Best total = 1.
Now brute force: try all merges:
- Merge 1->2: total 2
- Merge 1->3: sequence [3,2,3,2]? Actually merge 1->3: [3,2,3,2] sum=|3-2|+|2-3|+|3-2|=1+1+1=3 (worse)
- Merge 2->1: [1,1,3,1] sum=|1-1|+|1-3|+|3-1|=0+2+2=4
- Merge 2->3: [1,3,3,3] total 2
- Merge 3->1: [1,2,1,2] sum=|1-2|+|2-1|+|1-2|=1+1+1=3
- Merge 3->2: [1,2,2,2] total 1
So min is 1. So our algorithm yields minDelta = -2 for x=3, answer = 3-2=1. Good.
Thus algorithm works.
Now, test a case where median might not be unique but picking upper median works.
Consider x=5, neighbors: [1,4,6,9]. sum_orig = |5-1|+|5-4|+|5-6|+|5-9| =4+1+1+4=10. Sorted [1,4,6,9]; med = adj[2]=6 (upper median). sum_new = |6-1|+|6-4|+|6-6|+|6-9| =5+2+0+3=10, delta=0. If we pick lower median 4: sum_new = |4-1|+|4-4|+|4-6|+|4-9|=3+0+2+5=10, same. So fine.
Now, we also need to consider the possibility that best y might be x itself, but we skip because median might be different but delta computed from median will be <=0, and we compare with bestDelta. Since we compute delta for each x, and if median gives negative delta, that's fine. If median gives delta >0 (shouldn't happen), then we could still consider y=x which gives delta=0; but since we only compute median, we might miss that y=x could be better than median if median yields positive delta? But as argued, median yields minimal sum, which is at most sum at y=x. So sum_new <= sum_orig, so delta <=0. So median never yields positive delta. So it's safe.
But is there a scenario where we cannot set y to median because we have to merge to a page that exists? The merge target y must be a page number between 1 and n. The median from the neighbor list is within 1..n because neighbors are in that range. So it's allowed.
Thus algorithm correct.
Now, potential improvement: Instead of iterating over all x from 1 to n, we can iterate only over x that appear in the sequence? Actually x may appear but have no incident edges with different values (i.e., only edges with itself), then neighbors empty. But we can ignore those. Also x may not appear at all (if it's never in a). In that case, merging x does nothing, so delta=0. So we can skip. So we could collect only x that have non-empty neighbors. But iterating over all n (1e5) is fine.
Now, we need to ensure we use 64-bit for indices? Not needed.
Now, let's consider potential pitfalls with the reading of input: The numbers may be up to 1e5, and m up to 1e5, so reading is fine.
Now, final answer: Implement as described.
But wait, I recall that there might be a twist: The problem is from Codeforces Round #... Actually I've seen similar problem "Ryouko's Memory Note". I remember a solution that involves median. So this is correct.
Double-check the sample: Sample 1: T=5? Actually we computed T=5, but output 3. Our algorithm gave bestDelta -2, answer 3. Good.
Now, we should test a more complex case to be sure.
Consider n=5, m=7, a = [1,2,1,3,4,3,5].
Compute T manually? Let's do quickly.
Edges:
1-2:1
2-1:1
1-3:2
3-4:1
4-3:1
3-5:2
Sum=1+1+2+1+1+2=8
Now compute neighbors:
(1,2): adj1:2, adj2:1
(2,1): adj2:1, adj1:2
(1,3): adj1:3, adj3:1
(3,4): adj3:4, adj4:3
(4,3): adj4:3, adj3:4
(3,5): adj3:5, adj5:3
So:
adj1: [2,2,3]? Actually from (1,2) adds 2, (2,1) adds 2? Wait careful: (2,1) adds 1 to adj2 and 2 to adj1? Actually for (2,1), u=2, v=1: we add v to adj[u] => add 1 to adj[2]; add u to adj[v] => add 2 to adj[1]. So adj1 gets 2 from (1,2) and also 2 from (2,1)? Actually (1,2): adds 2 to adj[1] and 1 to adj[2]. (2,1): adds 1 to adj[2] and 2 to adj[1]. So yes, adj1: two entries of 2, and from (1,3): adds 3 to adj1. So adj1 = [2,2,3] (three entries). adj2: from (1,2): 1; from (2,1): 1; from ??? any other? No. So adj2 = [1,1] (two entries). adj3: from (1,3): 1; from (3,4): 4; from (4,3): 4; from (3,5): 5. So adj3 = [1,4,4,5] (four entries). adj4: from (3,4): 3; from (4,3): 3 -> [3,3]. adj5: from (3,5): 3 -> [3].
Now compute deltas:
x=1: sum_orig = |1-2|*2 + |1-3| = 1+1+2=4? Actually 1-2:1, second 1:1, 1-3:2 => sum=4. sorted [2,2,3]; med = index1 (since size 3, index1=0,1,2, s/2=1 -> med=2). sum_new = |2-2|+|2-2|+|2-3| = 0+0+1=1; delta = -3. So merging 1->2 yields new total 8-3=5.
Check manually: merge 1->2: sequence becomes [2,2,2,3,4,3,5]. Compute sum: edges: (2,2)=0, (2,2)=0, (2,3)=1, (3,4)=1, (4,3)=1, (3,5)=2 => total 5. matches.
x=2: sum_orig = |2-1|*2 = 1+1=2. sorted [1,1]; med = index1=1; sum_new = |1-1|+|1-1|=0; delta = -2; total = 6.
Merge 2->1: [1,1,1,3,4,3,5] sum: (1,1)=0,(1,1)=0,(1,3)=2,(3,4)=1,(4,3)=1,(3,5)=2 => total 6.
x=3: sum_orig = |3-1| + |3-4|*2 + |3-5| = 2 + (1+1) + 2 = 6? Actually |3-1|=2, |3-4|=1 (two times) ->2, |3-5|=2 => total 6. sorted [1,4,4,5]; med = index2 (size4, s/2=2) -> med=4. sum_new = |4-1|+|4-4|+|4-4|+|4-5| = 3+0+0+1=4; delta=-2; total=6.
Merge 3->4: [1,2,1,4,4,4,5]? Wait original after merging 3->4: a: 1,2,1,4,4,4,5? Actually original: [1,2,1,3,4,3,5]; replace all 3 with 4: becomes [1,2,1,4,4,4,5]. Sum: (1,2)=1,(2,1)=1,(1,4)=3,(4,4)=0,(4,4)=0,(4,5)=1 => total 6. Yes.
x=4: sum_orig = |4-3|*2 = 1+1=2. sorted [3,3]; med=3; sum_new=0; delta=-2; total=6.
Merge 4->3: [1,2,1,3,3,3,5] sum: (1,2)=1,(2,1)=1,(1,3)=2,(3,3)=0,(3,3)=0,(3,5)=2 => total 6.
x=5: sum_orig = |5-3|=2; sorted [3]; med=3; sum_new=0; delta=-2; total=6.
So best delta = -3 (x=1). Answer 5. So min total is 5.
Now, brute force maybe there is better? Try merge 5->3? That gave 6. Merge 1->3? Let's compute: merge 1->3: [3,2,3,3,4,3,5] sum: (3,2)=1,(2,3)=1,(3,3)=0,(3,4)=1,(4,3)=1,(3,5)=2 => total 6. So not better. So 5 is min.
Our algorithm gives 5. Good.
Now test case where x appears only in self edges? For example, a = [1,1,2,2,1,1]. T = 0+1+0+1+0=2? Actually edges: (1,1)=0, (1,2)=1, (2,2)=0, (2,1)=1, (1,1)=0 => T=2. Now neighbors:
(1,2) edge: adj1:2, adj2:1
(2,1) edge: adj2:1, adj1:2
Others (1,1) and (2,2) ignored.
So adj1 = [2,2]; adj2 = [1,1].
x=1: sum_orig = 1+1=2, med=2, sum_new=0, delta=-2 => total 0.
x=2: sum_orig = 1+1=2, med=1, sum_new=0, delta=-2 => total 0.
So best total 0. Indeed merging 1->2 or 2->1 yields all same pages: if merge 1->2 -> all 2's, sum 0. So correct.
Thus algorithm robust.
Now, possible oversight: The operation merges page x to y, but it copies information from x to y. It does not remove x. However, the sequence a now references y instead of x. There is no issue.
Now, is there any chance that merging x to y could affect the sum via edges that were originally (y, something) because the number of occurrences of y increases, but the edges themselves are unchanged? No.
Thus finalize.
But we must handle large input efficiently. Use scanf/printf or fast IO.
Now, potential memory: adj as vector of vectors of ints. For each x, we sort its vector; sorting modifies original adjacency but that's fine; we don't need the original after.
Now, one more nuance: In the computation of sum_orig, we use adj[x] before sorting, but sorting changes order, not values, so fine.
Now, consider that we might have duplicate edges; median handling with duplicates is fine.
Now, I'll write final solution.
But wait, think about the possibility that the best merge is not to a median because the target y must be an existing page? No, it can be any page 1..n, but median is among those.
Now, what about if the median is not the optimal because we also need to consider the effect on edges that become (y, y) from (x, x)? Those are zero anyway.
Thus final.
Now, let's produce the final answer.
But there is also alternative solution using prefix sums after sorting to compute sum_new quickly; but not needed.
Now, final code.
One more check: When we compute sum_orig, we should use long long, and when we compute sum_new, same.
Now, I think we're done.
However, before finalizing, recall that the problem statement says: "the answer can exceed 32-bit integers." So we must use 64-bit.
Now, submit.
But hold on: I recall there is a known Codeforces problem "Ryouko's Memory Note" (CF 433C?). I think there is a nuance: When we merge page x to page y, we also effectively change the "neighbors" of y because x disappears? Actually I think I've seen a solution where we consider the list of adjacent pages for each page, and then for each page we want to choose the best new value to minimize sum of distances to its adjacent pages. That's exactly median. But there is also a trick: we can only merge once, so we only change one page's value. So we consider each page as candidate to be merged (the source x) and choose best.
Yes, that's it.
But there is another twist: The problem states "she can apply the described operation at most once before the reading." So exactly one merge at most. So our approach is correct.
Now, we should also consider the possibility that we might merge a page that appears only once at the endpoint. For endpoint, there is only one incident edge; median is just that neighbor; so merging to neighbor yields reduction of the absolute difference (since |x - v| becomes 0). That's correct.
Now, time to write final solution.
But we must ensure that for x that appears but its neighbor list is empty (meaning all incident edges are self loops), we skip because merging does nothing. However, we could still consider merging such x to some y, but it would not affect any edges, because all edges are (x,x) become (y,y) and still 0. So Δ=0. So no impact.
Now, check with m=1: we output 0. In our code, we handle m==1 early. But if we didn't, then adj would be empty because there are no edges. T would be 0. For each x, adj[x] empty, skip, bestDelta=0, ans=0. That also works. But we would compute T as we loop through i from 0 to m-2, which would be no iterations, T=0. So we could skip the early return. But it's fine to keep it.
Now, verify with m=2, both values same: a=[5,5]. T=0. Edges: u=v so ignored, adj all empty, bestDelta=0, ans=0. Correct.
Now, test with m=2, values different: covered.
Now, consider scenario where the median is not the best due to constant offset? No.
Now, all good.
I think we can finalize.
But hold on, I realize something: The original sum T includes contributions from edges incident to x. In our Δ, we computed sum_new - sum_orig. However, we must ensure that we haven't double counted any change when the same edge appears in two different x? No, because Δ is computed per x and we consider merging only one x. So each edge change is counted exactly once in Δ for that x. Good.
Now, let's think about possibility that merging x to y could also affect the total sum through edges that are (x, v) and (v, x) - both are same edge? Actually an edge (x, v) is undirected but appears once in the sequence. So it's counted once. Our neighbor list includes each such edge once for x, so change is accounted. That's correct.
Now, I want to be absolutely certain that we didn't overlook the fact that the sum is over |a_i' - a_{i+1}'|. After merging, the sequence may have consecutive identical values, but that's fine.
Now, I'll produce final solution.
But there is a nuance: In the sample 1, we computed T=5. But they output 3 after merge. Our algorithm gave -2, correct.
Now, I'll write the final code accordingly.
One more thing: The problem uses 1-indexed pages. Our arrays are 1-indexed.
Now, go to final answer.
But wait, I recall that there is a known alternative solution using "mean" rather than median? But absolute differences minimized by median, not mean. So median is correct.
Now, I think we can implement.
But be careful: The sum of absolute deviations from median for a list can be computed efficiently with prefix sums, but we are fine with linear scan.
Now, code.
Potential bug: If we sort adj[x], we modify it; but we later might not need it again. So okay.
Now, I will write the solution.
I'll include comments for clarity.
Now, final answer.
But let's consider large case where a single x has many neighbors, say m=1e5, all edges involve x, so neighbors[x] size up to 2*(m-1) ~2e5. Sorting 2e5 integers is fine.
Now, test with random data using brute force for small n,m to ensure correctness. Since we are reasoning, we can trust.
Now, final code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int n, m;
scanf("%d%d", &n, &m);
vector<int> a(m);
for (int i = 0; i < m; ++i) scanf("%d", &a[i]);
if (m == 1) {
puts("0");
return 0;
}
ll total = 0;
vector<vector<int>> adj(n+1);
for (int i = 0; i < m-1; ++i) {
int u = a[i], v = a[i+1];
total += abs(u - v);
if (u != v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
}
ll bestDelta = 0; // if we do nothing
for (int x = 1; x <= n; ++x) {
if (adj[x].empty()) continue;
// compute original contribution sum |x - v|
ll sum_orig = 0;
for (int v : adj[x]) sum_orig += abs(x - v);
// find best y (median) to minimize sum |y - v|
sort(adj[x].begin(), adj[x].end());
int sz = adj[x].size();
int med = adj[x][sz / 2];
ll sum_new = 0;
for (int v : adj[x]) sum_new += abs(med - v);
ll delta = sum_new - sum_orig;
if (delta < bestDelta) bestDelta = delta;
}
ll ans = total + bestDelta;
printf("%lld\n", ans);
return 0;
}
But note: In the code, after sorting adj[x], we compute sum_new by iterating over sorted list. However, we could compute sum_new more efficiently using prefix sums, but it's fine.
One potential micro-optimization: We could compute sum_orig before sorting to avoid recomputing abs each time, but we already have sum_orig computed before sorting. That's fine.
Now, check for overflow: abs returns int; but difference up to 1e5, so product with 1e5 might exceed int? Actually we accumulate into long long, so fine.
Now, one more nuance: In the case where we have a large number of pages and we iterate over all x from 1 to n, that's up to 1e5, and for each we check if adj[x] is empty, which is O(1). So fine.
Now, consider case where m is 1, we return 0. But if we don't, the code would work as well because total = 0 (loop over edges does nothing), adj all empty, bestDelta=0, ans=0. So we could omit the early return. But keep it for clarity.
Now, I'm ready.
But I recall that there is a known mistake: Some solutions mistakenly consider that merging can only be done on pages that appear in the sequence. But we considered all x, including those that don't appear; they have empty adj, so they are skipped, so delta=0. So it's fine.
Now, I'll produce the final answer with explanation.
But the problem statement says: "She can apply the described operation at most once before the reading." So we assume we can choose to do nothing.
Now, final answer.
Double-check sample 1 with code: We'll get total = sum of |a_i - a_{i+1}| = |1-2|+|2-3|+|3-4|+|4-3|+|3-2| = 1+1+1+1+1=5. Then for x=4, adj[4] = [3,3]; sum_orig=2; med=3; sum_new=0; delta=-2; bestDelta becomes -2; ans=3. Good.
Sample2: total=5+1+5+0=11; x=9: adj[9]=[4]; sum_orig=5; med=4; sum_new=0; delta=-5; bestDelta=-5; ans=6.
Now, test with m=1: we return 0.
Everything seems consistent.
Thus final.
Now, consider potential alternative: Some might think that merging x to the average reduces sum, but median is correct.
Now, let's see if there is any scenario where the best y is not the median because we also need to consider edges that become (y, y) after merging? Those edges originally might be (x, x) and contribute 0, after merging become (y, y) also 0, so no effect. But what about edges that become (y, y) from (x, v) where v = y? Already accounted.
Thus median works.
Now, finalize.
But wait: Actually, there is another nuance: The sum T includes all edges. When we compute Δ for merging x, we used sum over edges incident to x. However, is it possible that an edge appears twice in the incident list for x? Each edge is counted exactly once for x. But what about edges where both endpoints are x? We ignored them, which is fine because they contribute 0 change. So total Δ computed is correct.
Now, the only tricky part left: The operation is to merge page x to page y. But what if we choose y = some value that is also being changed? No, only x changes.
Thus final.
Now, I will produce final answer.
But I just thought about something: The median may be computed as the lower median (floor) or upper median. For even length, both give same minimal sum. However, we used upper median (index sz/2). That's fine.
Now, consider a scenario: neighbors list size is even and the two middle numbers are 2 and 100. The minimal sum for any y between 2 and 100 is constant 98. So picking y=100 or 2 gives sum 98. But if x is 1, sum_orig = 1-2? Actually sum_orig = |1-2| + |1-100| = 1+99=100, delta = -2 if we pick y=2? Actually sum_new at y=2 is |2-2|+|2-100|=0+98=98, delta=-2; at y=100, sum_new = 98+0=98, delta=-2. So same. So no issue.
Now, I'm comfortable.
Now, additional optimization: Since we may compute sum_orig by iterating list before sorting, and after sorting we compute sum_new, we could compute sum_new using prefix sums to avoid second O(s) loop, but not needed.
Now, final answer: Provide explanation and code.
But the problem may have been from Codeforces and requires 64-bit output. Use %lld or cout.
Now, ensure we use long long consistently.
Now, write final solution.
Time complexity: O(m log m) due to sorting of neighbor lists, overall O(m log m). Space O(n+m).
Now, I'll produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> a(m);
for (int i = 0; i < m; ++i) cin >> a[i];
// If there is only one piece of information, no page turns are needed.
if (m == 1) {
cout << "0\n";
return 0;
}
// total turns in the original notebook
ll total = 0;
// adjacency list: for each page store the neighbouring values (multiset)
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m - 1; ++i) {
int u = a[i], v = a[i+1];
total += abs(u - v);
if (u != v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
}
ll bestDelta = 0; // best reduction (negative or zero)
for (int x = 1; x <= n; ++x) {
if (adj[x].empty()) continue; // merging this page does nothing
// original contribution of edges incident to x
ll sum_orig = 0;
for (int v : adj[x]) sum_orig += abs(x - v);
// find the median of the neighbour list – the optimal y
sort(adj[x].begin(), adj[x].end());
int sz = adj[x].size();
int med = adj[x][sz / 2]; // any median works
// new contribution after merging x to med
ll sum_new = 0;
for (int v : adj[x]) sum_new += abs(med - v);
ll delta = sum_new - sum_orig; // negative or zero
if (delta < bestDelta) bestDelta = delta;
}
ll answer = total + bestDelta;
cout << answer << '\n';
return 0;
}