`
445822357
  • 浏览: 742769 次
文章分类
社区版块
存档分类
最新评论

CF 337A (13.08.22)

 
阅读更多
A. Puzzles
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Sample test(s)
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.


题意:

我拿样例来说, 4是指人数, 6是指puzzle数

首先我们根据有多少人数, 就从puzzle中选多少个puzzle

然后在选出的puzzle中, 求出最大puzzle与最小puzzle之间的大小差~

最后, 在所有的差值中, 找最小的值


做法:

其实就是排序, 样例中可排成 22 12 10 10 7 5

我们可以看到, 排完序后, 若最大puzzle大小为22, 那么要求 最大-最小的差是最小的, 那么就选前四个22 12 10 10, 只有这样选, 最小值能保证尽量大! 从而差值小!

所以把这组数据分成 22 12 10 10 || 12 10 10 7 || 10 10 7 5 || 10 10 7 5 即可, 每组都是最大值减最小值, 再去比较那个差值最小!


AC代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>

using namespace std;

int cmp(int a, int b) {
    return a > b;
}

int main() {
    int n, m;
    int i, j;
    int puzzle[100];
    while(scanf("%d %d", &n, &m) != EOF) {
        for(i = 0; i < m; i++)
            scanf("%d", &puzzle[i]);

        sort(puzzle, puzzle+m, cmp);

        int min = 998;

        for(i = 0; i <= m-n; i++)
            if(puzzle[i] - puzzle[i+n-1] < min)
                min = puzzle[i] - puzzle[i+n-1];

        printf("%d\n", min);
    }
    return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics