CF:Codeforces Round 882 (Div. 2)A. The Man who became a God

10 篇文章 0 订阅

Problem - A - Codeforces

AC代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<cmath>
#include<numeric>
using namespace std;
#define endl '\n'
#define ll long long
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define pii pair<int,int>
const int N = 2e5 + 100;
void func()
{
	int n, k;
	cin >> n >> k;
	vector<int>a(n);
	vector<pii>dif(n-1);
	vector<int>vis(n, 0);
	for (auto& x : a)cin >> x;
	int ans = 0;
	int zu = n;
	if (k == n)//一组一个人
	{
		//k==1==n||k==n>1
		ans = 0;
	}
	else//k<n
	{
		if (k == 1)//一个组且k!=n即n>1
		{
			for (int i = 0; i + 1 < n; i++)
			{
				ans += abs(a[i + 1] - a[i]);
			}
		}
		else//1<k<n
		{
			for (int i = 0; i  < n-1; i++)
			{
				dif[i].first=abs(a[i + 1] - a[i]);
				dif[i].second = i;
			}
			//dif[0]--->0-1,dif[1]--->1-2
			sort(dif.begin(), dif.end());
			for (int i = 0; i < n - 1; i++)
			{
				if (i == 0)
				{
					ans += dif[0].first;
					vis[dif[0].second] = 1;
					vis[dif[0].second + 1] = 1;
					zu--;
				}
				else
				{
					if (vis[dif[i].second] == 0 && vis[dif[i].second + 1] == 0)
					{
						ans += dif[i].first;
						vis[dif[i].second] = 1;
						vis[dif[i].second + 1] = 1;
						zu--;
					}
					else if (vis[dif[i].second] == 0 && vis[dif[i].second + 1] == 1)
					{
						ans += dif[i].first;
						vis[dif[i].second] = 1;
						zu--;
					}
					else if (vis[dif[i].second] == 1 && vis[dif[i].second + 1] == 0)
					{
						ans += dif[i].first;
						vis[dif[i].second+1] = 1;
						zu--;
					}
					else
					{
						ans += dif[i].first;
						zu--;
					}
				}
				if (zu == k)break;
			}
		}
	}
	cout << ans << endl;
}
int main()
{
	cin.tie(0), cout.tie(0)->sync_with_stdio(false);
	int t;
	cin >> t;
	while (t--)
	{
		func();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值