#P9097. [PA 2020] Elektrownie i fabryki
[PA 2020] Elektrownie i fabryki
Problem Description
This problem is translated from PA 2020 Round 2 Elektrownie i fabryki.
To deal with the rising unemployment rate, the government of Byteotia decided to create new jobs. For this purpose, modern factories will be built, and new power plants will also be built to supply electricity to the factories.
A very long highway runs through Byteotia, and there are cities along it. For simplicity, we number the cities from to . Any two neighboring cities are exactly kilometer apart.
It has already been decided that some cities will build factories, and some other cities will build power plants. For the -th city, there is a value . If it is positive, then a power plant with capacity megawatts will be built in city . If it is negative, then a factory that consumes megawatts of electricity will be built in that city. If , then there is no construction plan for that city.
Your task is to design a power grid that transmits electricity from power plants to factories. For every pair of neighboring cities, you must decide whether to build a transmission line between them. If a city is connected, directly or indirectly, by transmission lines to some city that has a power plant, then electricity can flow from the power plant to the factory in that city. The design is correct if the electricity demand of every factory is satisfied. The cost of the grid is proportional to the total length (in kilometers) of all transmission lines.
Write a program to compute the minimum cost of designing a correct power grid.
Input Format
The first line contains an integer , the number of cities in Byteotia.
The second line contains integers , describing the production and consumption of electricity in each city.
Output Format
Output the minimum cost of a correct power grid design. If no correct design exists, output .
17
2 -5 0 2 0 0 0 4 0 0 -1 4 0 0 0 0 -3
12
Hint
Explanation of Sample 1
Below is a sample with cities, where three factories (white circles) and four power plants (black circles) will be built. A correct power grid of kilometers is marked in gray.

Constraints
This problem uses bundled testdata.
For some subtasks, .
For of the testdata, it is guaranteed that , .
Translated by ChatGPT 5