Video Solution
By David Zhou
Video Solution Code
Explanation
It is optimal to use each fence post at most once, so we can use BFS to find the minimum number of fence posts needed to direct the laser to the barn. We store the points on each horizontal and vertical line in . In the queue , we store the index of the point and the direction of the incoming beam. The array will store the number of edges of the shortest path from the laser to each point.
For every element in the queue, we process each unvisited point that the beam can be deflected to by adding it into the queue and updating its distance as one more than the current distance.
If we are able to deflect the beam to the barn, the number of mirrors needed is one less than the distance.
Implementation
Time Complexity:
C++
#include <cstdio>#include <iostream>#include <queue>#include <unordered_map>#include <vector>using namespace std;int main() {freopen("lasers.in", "r", stdin);freopen("lasers.out", "w", stdout);
Python
from collections import defaultdict, dequeclass Fencepost:def __init__(self, x: int, y: int):self.x = xself.y = ywith open("lasers.in", "r") as infile:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!