CF1922C Closest Cities
题目传送门
题面
There areThe distance between two cities
For each city
- the closest city to the city
is the city ; - the closest city to the city
is the city ; - the closest city to the city
is the city ; - the closest city to the city
is the city ; - the closest city to the city
is the city .
The cities are located in such a way that for every city, the closest city is unique. For example, it is impossible for the cities to be situated in points
You can travel between cities. Suppose you are currently in the city
- travel to any other city
, paying coins; - travel to the city which is the closest to
, paying coin.
You are given
Input
The first line contains one integer
Each test case is given in the following format:
- the first line contains one integer
( ); - the second line contains
integers ( ); - the third line contains one integer
( ); - then
lines follow; the -th of them contains two integers and ( ; ), denoting that in the -th query, you have to calculate the minimum number of coins you have to spend to travel from the city to the city .
Additional constraints on the input:
- in every test case, for each city, the closest city is determined uniquely;
- the sum of
over all test cases does not exceed ; - the sum of
over all test cases does not exceed .
Output
For each query, print one integer — the minimum number of coins you have to spend.
题目大意
数线上有
两个城市
您可以在城市之间旅行。假设您目前在城市
- 前往任何其他城市
,支付 金币; - 前往距离
最近的城市,支付 金币。
您会收到
思路
从 (想想为什么) 。
代码
#include <bits/stdc++.h> #define int long long #define endl '\n' using namespace std; void solve() { int n, m; cin >> n; vector<int> a(n + 1), b(n + 1, 0), c(n + 1, 0); for (int i = 1; i <= n; i++) { cin >> a[i]; } b[2] = 1; // 2号肯定是离1号最近的,所以1到2最小花费肯定是1 for (int i = 3; i <= n; i++) { if (a[i - 1] - a[i - 2] > a[i] - a[i - 1]) { b[i] = b[i - 1] + 1; // i-1最近的是i时,从i-1到i的最小花费肯定是1 } else { b[i] = b[i - 1] + a[i] - a[i - 1]; // i-1最近的不是i时,从i-1到i的最小花费是|a[i-1]-a[i]| } } c[n - 1] = 1; // 后缀和计算方式同上 for (int i = n - 2; i >= 1; i--) { if (a[i + 2] - a[i + 1] > a[i + 1] - a[i]) { c[i] = c[i + 1] + 1; } else { c[i] = c[i + 1] + a[i + 1] - a[i]; } } cin >> m; while (m--) { int x, y; cin >> x >> y; if (x < y) cout << b[y] - b[x] << endl; else cout << c[y] - c[x] << endl; } } signed main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); int t; cin >> t; while (t--) solve(); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下