-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathAMR10G.cs
72 lines (62 loc) · 3 KB
/
AMR10G.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
// https://www.spoj.com/problems/AMR10G/ #sorting
// Finds a set of K students from N total having the minimum height difference.
public static class AMR10G
{
// There are potentially many subsets of size costumeCount, but it doesn't make sense
// to consider all of them. Ignoring non-distinct heights (because it won't matter), every
// set of size costumeCount has a tallest student. There must be at least costumeCount - 1
// students shorter than that student, since it's tallest. So the potential tallest students
// are the last (studentCount - costumeCount) + 1 in an array of students sorted by height.
// We want the minimum difference though, so given we have the tallest student, we'd never go
// further back into the shorter students than absolutely necessary. So there'll be
// (studentCount - costumeCount) + 1 pairs of students to consider from the sorted array of heights.
// [ s s s s s s S S S S], 10 students, 7 costumes needed => 4 tallest students to consider.
public static int Solve(int studentCount, int costumeCount, int[] studentHeights)
{
if (costumeCount == 1)
return 0;
// Don't bother sorting in this case; easy to find the only possibility for tallest and shortest.
if (costumeCount == studentCount)
{
int heightOfShortest = studentHeights[0];
int heightOfTallest = studentHeights[0];
for (int s = 1; s < studentCount; ++s)
{
heightOfShortest = Math.Min(heightOfShortest, studentHeights[s]);
heightOfTallest = Math.Max(heightOfTallest, studentHeights[s]);
}
return heightOfTallest - heightOfShortest;
}
Array.Sort(studentHeights);
// Now consider the shortest/tallest pairs from the (studentCount - costumeCount) + 1 relevant subsets.
int minimumDifference = int.MaxValue;
for (int shortest = 0, tallest = costumeCount - 1; tallest < studentCount; ++shortest, ++tallest)
{
int heightOfShortest = studentHeights[shortest];
int heightOfTallest = studentHeights[tallest];
minimumDifference = Math.Min(minimumDifference, heightOfTallest - heightOfShortest);
}
return minimumDifference;
}
}
public static class Program
{
private static void Main()
{
int remainingTestCases = int.Parse(Console.ReadLine());
while (remainingTestCases-- > 0)
{
int[] line = Array.ConvertAll(
Console.ReadLine().Split(default(char[]), StringSplitOptions.RemoveEmptyEntries),
int.Parse);
int studentCount = line[0];
int costumeCount = line[1];
int[] studentHeights = Array.ConvertAll(
Console.ReadLine().Split(default(char[]), StringSplitOptions.RemoveEmptyEntries),
int.Parse);
Console.WriteLine(
AMR10G.Solve(studentCount, costumeCount, studentHeights));
}
}
}