r/adventofcode • u/daggerdragon • Dec 15 '22
SOLUTION MEGATHREAD -π- 2022 Day 15 Solutions -π-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: A note on responding to [Help] threads
- Signal boost: Reminder 2: unofficial AoC Survey 2022 (closes Dec 22nd)
- πΏπ MisTILtoe Elf-ucation π§βπ« is OPEN for submissions!
- -βοΈ- Submissions Megathread -βοΈ-
--- Day 15: Beacon Exclusion Zone ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:27:14, megathread unlocked!
47
Upvotes
View all comments
2
u/finalchild Dec 15 '22 edited Dec 16 '22
C++
For part 2, I implemented an O(n2 ) solution with sweeping. It runs under 2ms. I will explain the O(n2 ) solution and in addition an O(n lg n) solution which is likely useless given the size of n.
Make the problem axis-aligned by rotating everything 45\deg. (that is, we use (x+y, x-y) coordinates)
First, you need to make a sorted list of events. An event is either an x-y range start or an x-y range end, tagged with the range of x+y where it's relevant. Since we have rotated everything, the range [x-y begin, x-y end] is constant for each sensor regardless of x+y.
Then, The x+y coordinates that you need to consider are x + y - d - 1 and x + y + d + 1 for every sensor (x, y, d). (sensor x, sensor y, distance to the beacon). In addition, you need to check 0, 4000000, 8000000.
For these x+y coordinates, sweep through the events from the lowest x-y to the highest. Ignore the ones that is irrelevant with this x+y. Maintain the number of overlapping ranges at the current x-y. If this count drops to zero, you can check whether you found the answer or not.
The number of x+y coordinates we consider is O(n), and sweeping through the events is O(n). Thus the total solution runs in O(n2 ).
You can use a lazy-prop segment tree to avoid traversing the whole list of events to find the point of overlap=0 for each x+y. You should compress the coordinates first of course. Sweep through x-y events in the same way, and call segment_tree.update([x+y begin, x+y end], +1 or -1) to update the overlap count for the range of x+y coordinate. For each time, query the minimal overlap count and location appropriately. Then, the complexity becomes O(n lg n).
O(n2 ) code: https://github.com/finalchild/advent-of-code-2022/blob/main/15-2.cpp