Educational Codeforces Round 161 (Rated for Div. 2) 1922C - Closest Cities
Problem Link : https://codeforces.com/contest/1922/problem/C
Solution in C++:
- /// Author : AH_Tonmoy
- #include <bits/stdc++.h>
- using namespace std;
- int32_t main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- int t;
- cin >> t;
- while (t--) {
- int n;
- cin >> n;
- vector < int > a(n);
- for (int i = 0; i < n; i++) {
- cin >> a[i];
- }
- vector < int > forward(n), backward(n);
- forward[0] = 0;
- forward[1] = 1;
- for (int i = 2; i < n; i++) {
- if (a[i] - a[i - 1] < a[i - 1] - a[i - 2]) {
- forward[i] = forward[i - 1] + 1;
- } else {
- forward[i] = forward[i - 1] + a[i] - a[i - 1];
- }
- }
- backward[n - 1] = 0;
- backward[n - 2] = 1;
- for (int i = n - 3; i >= 0; i--) {
- if (a[i + 2] - a[i + 1] > a[i + 1] - a[i]) {
- backward[i] = backward[i + 1] + 1;
- } else {
- backward[i] = backward[i + 1] + a[i + 1] - a[i];
- }
- }
- int q;
- cin >> q;
- while (q--) {
- int x, y;
- cin >> x >> y;
- x--, y--;
- if (x < y) cout << forward[y] - forward[x] << '\n';
- else cout << backward[y] - backward[x] << '\n';
- }
- }
- return 0;
- }
No comments