周赛CodeForces 337A

Problem Description

The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).

The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on.

Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.

INPUT

The first line contains space-separated integers n and m (2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers f1, f2, ..., fm (4 ≤ fi ≤ 1000) — the quantities of pieces in the puzzles sold in the shop.

OUTPUT

Print a single integer — the least possible difference the teacher can obtain.

ex:

Input

4 6
10 12 10 7 5 22

Output

5

问题分析:先对物品按数量进行排序,利用STL中的sort函数

AC代码:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n, m;
	while (cin >> n >> m)
	{
		int a[55];
		for (int i = 0; i < m; i++)cin >> a[i];
		sort(a, a + m);
		int min2 = 999999999,t;
		for (int i = n - 1; i < m; i++)
		{
			t = a[i] - a[i - n + 1];
			if (min2 > t)min2 = t;
		}
		cout << min2 << endl;
	}
}

附加:sort函数用法:

1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std; 
  2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)
  
  3、Sort函数有三个参数:(第三个参数可不写)
  
  (1)第一个是要排序的数组的起始地址。
  
  (2)第二个是结束的地址(最后一位要排序的地址)
  
  (3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。
--------------------- 
作者:浅然_ 
来源:CSDN 
原文:https://blog.csdn.net/w_linux/article/details/76222112 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值