CF EDU 127 D - Insert a Progression

D - Insert a Progression

绝对值

image

首先算出不插入时的答案

  1. 如果插入的数在 [minn, maxn] 中,则没有代价

  2. 如果 x > maxn, 则有 (maxn,x] 这些数要产生代价,把他们放到最大值后面,则代价为 2(xmaxn)

    若放到开头或结尾,则代价是 xa[1]xa[n], 三者取最小值

  3. 如果 minn > 1, 同理

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>

using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int n, x;
int a[N];
int main()
{
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	int T;
	cin >> T;
	while(T--)
	{
		cin >> n >> x;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		ll ans = 0;
		int maxn = a[1], minn = a[1];
		for (int i = 2; i <= n; i++)
		{
			ans += abs(a[i] - a[i-1]);
			maxn = max(maxn, a[i]);
			minn = min(minn, a[i]);
		}
		if (minn > 1)
		{
			int add = min({2 * (minn - 1), a[1] - 1, a[n] - 1});
			ans += add;
		}
			
		if (maxn < x)
		{
			int add = min({2 * (x - maxn), x - a[1], x- a[n]});
			ans += add;
		}
		cout << ans << endl;
	}
	return 0;
}

posted @   hzy0227  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示