-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathGLJIVE.cs
86 lines (74 loc) · 2.63 KB
/
GLJIVE.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
// https://www.spoj.com/problems/GLJIVE/ #ad-hoc #binary #sequence
// Finds the contiguous subsequence starting from 1 that most closely adds to 100.
public static class GLJIVE
{
// Actually, the work below is wrong. We're looking for a contiguous subsequence
// starting from the first index, but not necessarily spanning all 10.
public static int SolveCorrectly(int[] points)
{
int result = 0;
for (int i = 0; i < 10; ++i)
{
if (result + points[i] <= 100)
{
result += points[i];
}
else // points[i] pushes us over 100...
{
// So if the distance now is worse than (or equal to) the distance
// after adding it, add it.
if (100 - result >= result + points[i] - 100)
{
result += points[i];
}
// And then stop, since adding more will only take us further away.
break;
}
}
return result;
}
// This is like subset sum but not sure I want to use DP to solve it, since
// the numbers we're working with are so well-defined. Instead, I'll try to
// brute force over the 2^10 - 1 subsets, - 1 since at least one value is needed.
public static int SolveIncorrectly(int[] points)
{
int bestResult = 0;
int bestDistance = 100;
// Each i corresponds to a different subset, based upon its binary representation
// For example, 17 = 0000010001, 0th and 4th points included, 1023 = 1111111111,
// all points included.
for (int i = 1; i <= 1023 && bestDistance != 0; ++i)
{
int result = 0;
for (int j = 0; j <= 9; ++j)
{
if ((i & (1 << j)) != 0) // The jth bit is turned on.
{
result += points[j];
}
}
int distance = 100 >= result ? 100 - result : result - 100;
// If it's closer, or it's the same distance but on the greater-than side of 100...
if (distance < bestDistance || distance == bestDistance && result > bestResult)
{
bestResult = result;
bestDistance = distance;
}
}
return bestResult;
}
}
public static class Program
{
private static void Main()
{
int[] points = new int[10];
for (int i = 0; i < 10; ++i)
{
points[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine(
GLJIVE.SolveCorrectly(points));
}
}