private void insert(heapnode node, heapnode[] heap) { heap[heapcount++] = node; for (int i = heapcount / 2; i >= 0; i--) { heapify(i, heap); } }
private heapnode getMax(heapnode[] heap) { heapnode node = heap[0]; heap[0] = heap[heapcount - 1]; heapcount--; heapify(0, heap); return(node); }
public List <int> solve(List <int> A, List <int> B) { List <int> res = new List <int>(); if (A == null && B == null) { return(res); } if (A.Count < 0) { return(res); } A.Sort((a, b) => - 1 * a.CompareTo(b)); B.Sort((a, b) => - 1 * a.CompareTo(b)); int length = A.Count; heap = new heapnode[length]; heapnode node; int i, j; i = 0; j = 0; node = new heapnode(i, j, A[i] + B[j]); insert(node, heap); string key = string.Format("{0}{1}", i, j); dict.Add(key, true); int sum = 0; for (int k = 0; k < length; k++) { heapnode curr = getMax(heap); res.Add(curr.sum); i = curr.i; j = curr.j; key = string.Format("{0}{1}", i + 1, j); if ((i + 1) < length && !dict.ContainsKey(key)) { sum = A[i + 1] + B[j]; insert(new heapnode(i + 1, j, sum), heap); dict.Add(key, true); } key = string.Format("{0}{1}", i, j + 1); if ((j + 1) < length && !dict.ContainsKey(key)) { sum = A[i] + B[j + 1]; insert(new heapnode(i, j + 1, sum), heap); dict.Add(key, true); } } return(res); }
private void heapify(int i, heapnode[] heap) { int left = 2 * i + 1; int right = 2 * i + 2; int largest = i; if (left < heap.Length && heap[left] != null && heap[left].sum > heap[largest].sum) { largest = left; } if (right < heap.Length && heap[right] != null && heap[right].sum > heap[largest].sum) { largest = right; } if (largest != i) { heapnode temp = heap[largest]; heap[largest] = heap[i]; heap[i] = temp; heapify(largest, heap); } }