An invalid opcode exception typically implies either one of the following two scenarios:
An assert(cond) statement with cond == false
An array[i] expression with i >= array.length
You don't have any assert statements in your code, so you should start by looking into every x[y] statement.
However, some of those statements in your code are with x being a ...
I got a little lost in it, in part because we can't see the whole thing and in part because the data structure is leading to convoluted code. You eluded to that.
Btw. I realize that arrays are a terrible data structure for what I'm trying to do to begin with. If Solidity has better data structures available (like a binary heap for starters), please let ...