[CodeForces-337A] A. Puzzles【水题】

A. Puzzles

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.

Examples
inputCopy
4 6
10 12 10 7 5 22
outputCopy
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.

链接:http://codeforces.com/problemset/problem/337/A

简述:n个学生,有m块披萨可以选,每块披萨的值不一样,从m块披萨中选取n块披萨使到这n块披萨的最大值跟最小值的差最小。

分析:首先排序找规律,一开始我找到了任意两块披萨的最小值,发现不对,因为从m块披萨中选取n块披萨使得所求最小值跟任意两个的最小值是不一样的。所求为任意n块披萨的最小值。依然是排序,使用镶嵌循环,使到两个数间隔n位数(包括自身)再求差,得最小值。

说明:min()函数有时用了头文件编译器也不给过,它提示参数为double。

AC代码如下:

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
	int n, m, i ,t , a[1010], j;
	double minn = 1e6;
	cin >> n >> m;
	for (i = 1; i <= m; i++)
		cin >> a[i];
	for (i = 1; i <= m; i++)
		for (j = i + 1; j <= m; j++)
			if (a[i] > a[j]) {
				t = a[i];
				a[i] = a[j];
				a[j] = t;
		}
	for (i = 1; m - i < n, n <= m; i++)
	{
		minn = min(minn, (double)a[n] - a[i]);
		n++;
	}
	cout << minn << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_43966202/article/details/86755925
今日推荐