Codeforces Round #822 (Div.2)-A. Select Three Sticks

链接:Problem - A - Codeforces

You are given n sticks with positive integral length a1,a2,…,an.

You can perform the following operation any number of times (possibly zero):

choose one stick, then either increase or decrease its length by 1. After each operation, all sticks should have positive lengths.
What is the minimum number of operations that you have to perform such that it is possible to select three of the n sticks and use them without breaking to form an equilateral triangle?

An equilateral triangle is a triangle where all of its three sides have the same length.

Input
The first line of the input contains a single integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (3≤n≤300) — the number of sticks.

The second line of each test case contains n integers a1,a2,…,an (1≤ai≤109) — the lengths of the sticks.

It is guaranteed that the sum of n over all test cases does not exceed 300.

Output
For each test case, print one integer on a single line — the minimum number of operations to be made.

Example
input

4
3
1 2 3
4
7 3 7 3
5
3 4 2 1 1
8
3 1 4 1 5 9 2 6
output
2
4
1
1

题意:在数组中任选一个数+1或-1,求让数组中至少存在三个相同的数的最小操作次数。

假设有a, b, c三个数(a<=b<=c),如果要让a,b,c三个数相等,最小操作次数为 b-a + c-b = c - a
当c和a差距最小时,操作次数最小,所以先对数组从小到大排序(从大到小也行), 求出每个三元组(a, b, c)中最小的c-a即可。

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int nums[305];
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	int t;
	cin >> t;
	while(t --)
	{
		int n, ans = 0x3f3f3f3f;
		cin >> n;
		for(int i=0; i<n; i++) cin >> nums[i];
		sort(nums, nums+n);
		for(int i=2; i<n; i++)
			ans = min(ans, nums[i]-nums[i-2]); //求三元组(nums[i-2], nums[i-1], nums[i]) nums[i] - nums[i-2] 最小的 
		cout << ans << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值