C - Puzzles

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 - Bis 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.

Examples

Input
4 6
10 12 10 7 5 22
Output
5

Note

Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5.

解题思路:题目的意思就是从m块pizza中选择n块(n<=m),要求这n块pizza中尺寸最大与尺寸最小之差是所有选择中的最小差值。做法:先将pizza的尺寸按升序排序,然后从n-1开始依次枚举到m-1,则[i-n+1,i]构成连续排列的n块pizza的尺寸区间,接下来取其差值和最小值minc比较,依次更新最小值minc。为什么连续取n块pizza呢?因为如果去掉该区间中的1或2个元素,从其他区间中挑选1个或2个元素加入其中,此时的区间范围必将向前或向后延伸(变大),这样会使得差值增大,显然不符合条件要求。

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main(){
 4     int n,m,a[55],minc=1005;
 5     cin>>n>>m;
 6     for(int i=0;i<m;++i)cin>>a[i];
 7     sort(a,a+m);
 8     for(int i=n-1;i<m;++i)
 9         minc=min(minc,(a[i]-a[i-n+1]));
10     cout<<minc<<endl;
11     return 0;
12 }

猜你喜欢

转载自www.cnblogs.com/acgoto/p/9141581.html
C