周赛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 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_43966635/article/details/86593728