103 - ZOJ Monthly, February 2011 - I
Long long ago, in the forgotten land, there is a rich country named X. There were several countries in the forgotten land and some of them were so aggressive that they often invade other countries, including X. X was so rich but its army was not strong enough to beat these invaders totally. So, the king of country X decided to build a national defense system to prevent the attack from other countries. The main part of the system is the great wall!
As far as the king knew, the map of the forgotten land is a rectangle with n * m grids, and each country occupied a single grid.
Some allied countries nearby want to join the system and were willing to pay some money for it to prevent themselves from the attack from those aggressive countries.
Now, knowing how much money each country was willing to pay and the cost to build wall at each board, the king must decide which countris are accepted to make the total cost at low at possible.
If a country has been accepted to join in the defense system, it will be safe when the great wall is done. Safe means that it's impossible to invade the country without destroying some part of the great wall from those aggressive countries (maybe some unknown country from the outside of the map).
For example, in the above map, X means country X, E means the aggressive country and A means the allied country. The cost to build great wall along each red border is 1 million doller and the cost to build great wall along each black border is 10 million doller. If the allied country afford more than 8 million doller, the best way is to build the great wall along the yellow curve. But if it cannot afford 8 million doller for the great wall, the best way is to build the great wall along the bule curve, just surrounding X.
There are about a hundred cases.
A single integer, the minimum cost. Note that the cost can be negative when country X can earn money from the building of the great wall. .
3 3 1 1 1 1 10 10 1 10 1 10 1 1 1 1 10 1 10 1 10 10 1 1 1 1 3 0 0 0 -1 1 1 100 2 2 3 3 1 1 1 1 10 10 1 10 1 10 1 1 1 1 10 1 10 1 10 10 1 1 1 1 3 0 0 0 -1 0 1 9 2 2
Author: WANG, Yelei
Contest: ZOJ Monthly, February 2011