1.17第四题

D - 4

Time limit 1000 ms
Memory limit 262144 kB

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.

Sample Input

4 6
10 12 10 7 5 22

Sample Output

5

问题链接:CodeForces - 337A

问题简述:

输入n代表需要的拼图数,输入m代表拼图的种类数,接下来输入m个数代表每种拼图的所包含的数量,求筛选出n种拼图,使得拼图数量的最大值与最小值的差为最小

问题分析:

排序,然后往右推做差求出最小值,例如要4块拼图有6种拼图,则计算a[4]-a[1](这里第一块拼图为a[1]而不是a[0],仅作为一种说明方便理解),然后继续a[5]-a[2],a[6]-a[3],然后取差值的最小值作为输出

程序说明:

用冒泡排序或者利用sort函数进行排序。

AC通过的C语言程序如下:

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n, m;
	cin >> n;
	cin >> m;
	int a[100];
	int temp;
	int finally;
	for (int i = 1;i <= m;i++)
	{
		cin >> a[i];
	}
	for (int i = 1;i <= m;i++)
	{
		for (int j = 1;j <= m - 1;j++)
		{
			if (a[j] > a[j + 1])
			{
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
	finally = a[n] - a[1];
	for (int i = 1;i <= m - n;i++)
	{
		finally = min(a[i + n ] - a[i+1], finally);
	}
	cout << finally;
}


也可用sort算法来排序,需要加入头文件algorithm()

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n, m;
	cin >> n;
	cin >> m;
	int a[100];
	int temp;
	int finally;
	for (int i = 1;i <= m;i++)
	{
		cin >> a[i];
	}
	sort(a + 1, a + m + 1);
	finally = a[n] - a[1];
	for (int i = 1;i <= m - n;i++)
	{
		finally = min(a[i + n ] - a[i+1], finally);
	}
	cout << finally;
}

猜你喜欢

转载自blog.csdn.net/weixin_44003969/article/details/86555133
今日推荐