Sailboat
Time limit1sMemory limit128 MB
Find a path from buoy 1 to buoy n in a DAG maximizing the sum of squared differences between consecutive edge weights.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Graph, Shortest path
- Solved
- No attempts yet
Problem
Winnie the Pooh set out on a sailing trip with Tigger. Tigger is an experienced sailor and steers the boat, while Pooh, a landlubber, is a little scared. Every time the boat changes its heading, the wind changes the boat's heel (tilt) angle. Each such change makes Pooh cry out loudly: the larger the change in heel, the louder he shouts, but the more of an adventure he collects. Pooh's total thrill from the trip is the sum of the squares of every heel change between two consecutive segments. Help Tigger maximize it.
The trip starts at Piękna Góra and ends at Sztynort. Turns may be made only at the marked buoys. From every buoy you may sail only along fixed routes, and every route always leads to a buoy with a higher number than the current one. Buoy number stands at the start (Piękna Góra) and buoy number stands at the finish (Sztynort). Every route segment joining two buoys has a fixed heel value given in the input. Because the boat must motor in and out of the harbor, every segment leaving the start and every segment entering the finish has heel .
If the segments traversed in order have heels , then
is Pooh's total thrill. Your task is to compute the maximum possible value of this sum.
Write a program that:
- reads the description of the routes from standard input,
- computes the maximum thrill of the trip,
- writes the result to standard output.
Input
The first line contains two integers and separated by a single space, where and .
Each of the next lines contains three integers , , and separated by single spaces. The numbers and are the buoys joined by this segment, with . The number is the heel of the boat on this segment, with . If (the start) or (the finish), then .
Output
Print a single integer: the maximum thrill Pooh can get from the trip.