Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define task "LCD"
- #include <iostream>
- #include <cstdio>
- using namespace std;
- using ll = long long;
- using ld = long double;
- constexpr int N = 1e6 + 5;
- constexpr ll Inf = 1e17;
- int n, m;
- int a[N];
- ll b[N * 2];
- void Read()
- {
- cin >> n >> m;
- for (int i = 1; i <= n; ++i)
- {
- cin >> a[i];
- --a[i]; /// Change 1, 2, ..., m -> 0, 1, 2, ..., (m - 1)
- }
- }
- void Solve()
- {
- ll sum(0); // Answer without X
- for (int i = 1; i < n; ++i)
- {
- if (a[i] > a[i + 1])
- a[i + 1] += m;
- sum += a[i + 1] - a[i];
- b[a[i] + 2] += 1;
- b[a[i + 1] + 1] += -1 - (a[i + 1] - a[i] - 1);
- b[a[i + 1] + 2] += (a[i + 1] - a[i] - 1);
- if (a[i + 1] >= m)
- a[i + 1] -= m;
- }
- for (int i = 1; i < m * 2; ++i)
- b[i] += b[i - 1];
- for (int i = 1; i < m * 2; ++i)
- b[i] += b[i - 1];
- ll ans(Inf);
- for (int i = 0; i < m; ++i)
- ans = min(ans, sum - b[i] - b[i + m]);
- cout << ans;
- }
- int32_t main()
- {
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- if (fopen(task ".INP", "r"))
- {
- freopen(task ".INP", "r", stdin);
- freopen(task ".OUT", "w", stdout);
- }
- Read();
- Solve();
- }
- /*
- 4 5
- 1 2 4 5
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement