gpt4 book ai didi

algorithm - SPOJ 水 : Developing a BFS algorithm

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:49:40 26 4
gpt4 key购买 nike

我正在尝试解决 SPOJ 中的以下问题:

On a rectangular mesh comprising nm fields, nm cuboids were put, one cuboid on each field. A base of each cuboid covers one field and its surface equals to one square inch. Cuboids on adjacent fields adhere one to another so close that there are no gaps between them. A heavy rain pelted on a construction so that in some areas puddles of water appeared.

Task

Write a program which:

  • reads from the standard input a size of the chessboard and heights of cuboids put on the fields
  • computes maximal water volume, which may gather in puddles after the rain
  • writes results in the standard output.

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case two positive integers 1 <= n <= 100, 1 <= m <= 100 are written. They are the size of the mesh. In each of the following n lines there are m integers from the interval [1..10000]; i-th number in j-th line denotes a height of a cuboid given in inches put on the field in the i-th column and j-th raw of the chessboard.

Output

Your program should write for each tes case one integer equal to the maximal volume of water (given in cubic inches), which may gather in puddles on the construction.

Example

Sample input:
1
3 6
3 3 4 4 4 2
3 1 3 2 1 4
7 3 1 6 4 1

Sample output:
5

我正在使用 BFS 来添加从边界元素流入水坑的水量(如果找到任何路径)。但是我无法处理水坑可能像两个连续的长方体的情况。谁能帮我处理那个案子?

最佳答案

这是我对这个问题的回答。为了表述方便,我假设索引从(1,1)开始到(M,N)

就像你想象的水流一样,水只能从较高的长方体流向较低的长方体(没有反向方向,即来自较低长方体的水会撞到较高长方体的壁并停在那里)。

所以我们构建图 G = (V,E) 使得 V 是 M x N 顶点,即矩阵上的长方体。当连接长方体 i(th) 和长方体 j(th) 时,边被连接(仅单向)height(i) >= height(j) and (i and j are physically CONNECTED)

所以问题只是一个简单的 BFS。

顺便说一下,我发现另一个也能解决这个问题。请看一下

http://www.spojsolutions.com/212-water-among-cubes/

关于algorithm - SPOJ 水 : Developing a BFS algorithm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com