Explanation
We process the branches from lowest to highest, calculating for each branch the amount of area it has that is not covered by a subsequent one. Looking at the image of the sample case given in the problem statement, we would be calculating the area outlined in black for each branch.
For each branch, there are two cases:
- No branch covers the current one. In this case, we add to the total, as that is the formula for the area of a triangle.
- A branch covers the current one, turning it into a trapezoid. In this case, we need to use the formula for the area of a trapezoid, which is , where and are the lengths of the top and bottom bases.
Implementation
Time Complexity:
C++
#include <algorithm>#include <iomanip>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;/** @return the area of a trapezoid with the given base lens and height */
Python
def trap_area(base1: float, base2: float, height: float) -> float:""":return: the area of a trapezoid with the given base lens and height"""return height * (base1 + base2) / 2for _ in range(int(input())):branch_num, base, height = [int(i) for i in input().split()]offsets = sorted(int(i) for i in input().split())assert branch_num == len(offsets)
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!