Problem:
Score : 400 points

Problem Statement

We have a grid with H rows and W columns of squares.
Snuke is painting these squares in colors 1, 2, ..., N.
Here, the following conditions should be satisfied:

For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.

For each i (1 ≤ i ≤ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

1 ≤ H, W ≤ 100

1 ≤ N ≤ H W

a_i ≥ 1

a_1 + a_2 + ... + a_N = H W

Input

Input is given from Standard Input in the following format:

H W
N
a_1 a_2 ... a_N

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}

Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color 1 are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

1 4 4 4 3
2 5 4 5 3
2 5 5 5 3

Sample Input 3

1 1
1
1

Sample Output 3

1

Solution in Scala (2.11.7) (judge verdict: Accepted)

import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val Array(h, w) = in.readLine().split("\\s+").map(_.toInt)
    val n = in.readLine().toInt
    val as = in.readLine().split("\\s+").map(_.toInt)
    val grid = Array.ofDim[Int](h, w)

    @tailrec
    def coloring(totalCount: Int, as: List[(Int, Int)]): Unit = {
      val x = if (totalCount % (2 * w) < w) {
        totalCount % (2 * w)
      } else {
        w - 1 - totalCount % w
      }
      val y = totalCount / w

      as match {
        case (color, count) :: rest =>
          System.err.println(s"(${y})(${x}) = ${color}")
          grid(y)(x) = color
          if (count > 1) {
            coloring(totalCount + 1, (color, count - 1) :: rest)
          } else {
            coloring(totalCount + 1, rest)
          }
        case Nil =>
      }
    }

    coloring(0, as.zipWithIndex.map { case (a, index) =>
      (index + 1, a)
    }.toList)

    for (y <- 0 until h) {
      out.println(grid(y).mkString(" "))
    }

    out.flush()
  }
}