Skip to main content
Back to problems
Codeforces
Easy
Arrays
Math
Xenia and Ringroad

Compute the total time needed to visit a sequence of houses on a circular ring road.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Xenia and Ringroad

A ring road has houses numbered from $1toton in clockwise order. Xenia starts at house \1$ and needs to visit a given sequence of houses in order.

Moving from one house to the next adjacent house takes one unit of time. Because the road is circular, after house nn comes house $1$.

Your task is to determine the total time required for Xenia to complete the entire sequence of visits.

Task

Given the number of houses and the list of houses to visit, simulate the movement along the ring road and sum the distances traveled for each step.

Input Format

  • The first line contains two integers nn and mm — the number of houses on the ring road and the number of houses to visit.
  • The second line contains mm integers a1,a2,,ama_1, a_2, \dots, a_m — the sequence of houses Xenia must visit in order.

Output Format

  • Print one integer: the total time needed to visit all houses in the given order.

Constraints

  • 1n,m1051 \le n, m \le 10^5
  • 1ain1 \le a_i \le n
  • Xenia starts at house $1$
Examples
Sample cases returned by the problem API.

Example 1

Input

4 3
3 2 3

Output

6

Explanation

Start at 1.

  • Go to 3: 2 steps.
  • Go to 2: 3 steps (3 -> 4 -> 1 -> 2).
  • Go to 3: 1 step. Total = 6.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.