public int Solve(int K, int M, int[] A) { var(upper, max) = Init(A, K); var aims = BSHelper.Generate(max, upper - 1); int lastAim = upper; foreach (var aim in aims) { if (TryOne(A, aim.Index) <= K) { lastAim = aim.Index; aim.Dir = -1; } else { aim.Dir = 1; } } return(lastAim); }
int Solve(int[] A) { if (A.Length < 2) { return(Math.Abs(A[0]) * 2); } Array.Sort(A); var bin = BSHelper.Generate(0, A.Length - 1); var lastIndex = -1; foreach (var b in bin) { var a = A[b.Index]; lastIndex = b.Index; if (a < 0) { b.Dir = 1; } else if (a > 0) { b.Dir = -1; } else { break; } } if (A[lastIndex] == 0 && lastIndex > 0 && A[lastIndex - 1] == 0 || lastIndex < A.Length - 1 && A[lastIndex + 1] == 0) { return(0); } int i, j; if (A[lastIndex] < 0) { i = lastIndex; j = lastIndex + 1; if (j >= A.Length) { return(-A[i] * 2); } } else { i = lastIndex - 1; j = lastIndex; if (i < 0) { return(A[j] * 2); } } var min = int.MaxValue; for (; ;) { var sum = A[i] + A[j]; var abssum = Math.Abs(sum); if (abssum < min) { min = abssum; } if (i > 0 && j < A.Length - 1) { var newLeft = Math.Abs(A[i - 1] + A[j]); var newRight = Math.Abs(A[i] + A[j + 1]); if (newLeft < newRight) { i--; } else { j++; } } else if (i > 0) { if (sum > 0) { i--; } else { break; } } else if (j < A.Length - 1) { if (sum < 0) { j++; } else { break; } } else { break; } } return(min); }
public int Solve(int[] A, int[] B, int[] C) { var pairs = new Pair[C.Length]; for (var i = 0; i < C.Length; i++) { var pair = new Pair { Step = i + 1, NailPos = C[i] }; pairs[i] = pair; } Array.Sort(pairs); pairs = Cleanup(pairs).ToArray(); var minNeeded = 0; for (var i = 0; i < A.Length; i++) { var a = A[i]; var b = B[i]; var bin = BSHelper.Generate(0, pairs.Length - 1); int index = -1; foreach (var z in bin) { var p = pairs[z.Index]; if (a <= p.NailPos && p.NailPos <= b) { index = z.Index; break; } else if (b < p.NailPos) { z.Dir = -1; } else if (p.NailPos < a) { z.Dir = 1; } } if (index < 0) { return(-1); } var step = pairs[index].Step; if (step > minNeeded) { for (var j = index + 1; j < pairs.Length && pairs[j].NailPos <= b; j++) { if (pairs[j].Step < step) { step = pairs[j].Step; if (step <= minNeeded) { break; } } } } if (step > minNeeded) { for (var j = index - 1; j >= 0 && pairs[j].NailPos >= a; j--) { if (pairs[j].Step < step) { step = pairs[j].Step; if (step <= minNeeded) { break; } } } } if (step > minNeeded) { minNeeded = step; } } return(minNeeded); }