ASM – The Abelian Sandpile Model
Time limit1sMemory limit128 MB
Drop grains one at a time on a grid and repeatedly topple any cell over the critical height, losing grains that fall off the edge, until the pile is stable.
- Level
Medium5 of 10
- Topics
- Simulation, Queue, Implementation, Matrix
- Solved
- No attempts yet
Problem
Modelling sandpiles is an interesting problem in statistical physics. When you drop a grain of sand onto an existing pile, most of the time the grain simply sticks, or a few grains slide down. Occasionally, however, adding a single extra grain triggers a huge avalanche of sand.
A simple way to model this is the Abelian Sandpile Model. Here the sandpile is a two-dimensional lattice, and each lattice site holds a height (the number of grains on that site). Dropping a grain on a site increases its height by one. If a site's height ever becomes larger than a fixed critical height, the site topples: its height is reduced by four, and each of its four orthogonal neighbours gains one grain. Toppling can push neighbours above the critical height, so they topple in turn, and so on until every site is stable again. Any grain that would leave the lattice is lost.
Given an initial sandpile and the positions at which grains are dropped, determine the final (stable) sandpile.
Input
The first line contains a single integer , the number of test cases. Each test case has the following format:
- One line with four integers , , , and where , , and : the height and width of the lattice, the number of dropped grains, and the critical height.
- lines follow, each with characters in the range
0to9: the heights of the initial sandpile. Every initial height is at most the critical height. - lines follow, each with two integers and where and : the positions (row, column, 1-indexed) where grains are dropped.
Output
For each test case, output lines, each with characters in the range 0 to 9: the heights of the final sandpile.