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



Sample input:
2 2
3
2 1 1


Sample output:
1 1
2 3

Submission status: Accepted

Solution code:
import sys
from collections import deque
import copy
import numpy as np

from math import *
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [H, W] = [int(input_raw[0]), int(input_raw[1])]
    input_raw = read_func().strip().split()
    [N] = [int(input_raw[0])]
    input_raw = list(read_func().strip().split())
    #color_num_list = []
    #color_num_list = {}
    color_num_list = np.zeros((N))
    for i in range(N):
        color_num_list[i] = (int(input_raw[i]))

    index_list = np.argsort(color_num_list)[::-1]
    sorted_color_num = np.sort(color_num_list)[::-1]

    mat = np.zeros((H, W),'int')
    now_i = 0
    now_j = 0
    rev_flag = False
    #tmp_color_num_list = copy.deepcopy(color_num_list)
    #while len(color_num_list) > 0:
        #color_num = max(color_num_list.values())
        #color = color_num_list.keys()[color_num_list.values().index(color_num)]
        #color_num_list.pop(color)
        #tmp_color_num_list.remove(color_num)
    for i in range(N):
        color_num = sorted_color_num[i]
        color = index_list[i] + 1
        while color_num > 0:
            mat[now_i][now_j] = color
            if (now_j < W - 1 and rev_flag == False)  or  (now_j >= 1 and rev_flag == True):
                s = -1 if rev_flag == True else 1
                now_j += s
            else:
                now_i += 1
                rev_flag = not(rev_flag)
            color_num -= 1

    for i in range(H):
        for j in range(W):
            print mat[i][j],
        print


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

import numpy as np

[H, W] = [int(i) for i in input().split()]
N = int(input())
a = [int(i) for i in input().split()]

ans_flat = []
for i in range(len(a)):
    for j in range(a[i]):
        ans_flat.append(i + 1)

ans_flat = np.array(ans_flat)
ans_sq = ans_flat.reshape(H,W)

for i in range(H):
    if i % 2 == 1:
        ans_sq[i] = ans_sq[i][::-1]
    print(' '.join(ans_sq[i].astype(str)))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))

out = [[0 for _ in range(W)] for _ in range(H)]

index = [0, 0]
sign = 1
for color in range(N):
    for number in range(a[color]):
        out[index[0]][index[1]] = color + 1
        if index[0] == H - 1 and sign == 1:
            index[1] += 1
            sign = -1
        elif index[0] == 0 and sign == -1:
            sign = 1
            index[1] += 1
        else:
            index[0] += sign

for i in range(H):
    [print(x, end=' ') for x in out[i]]
    print()

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    N = int(input())
    a = list(map(int, input().split()))

    flatten = []
    for i in range(0, N):
        flatten.append([(i + 1) for j in range(a[i])])
    flatten_2 = []
    for tmp in flatten:
        flatten_2.extend(tmp)
    # print(flatten_2)
    ans = [[] for i in range(H)]

    for i in range(0, H):
        if i % 2 == 0:
            ans[i] = list(map(str, flatten_2[i * W:(i + 1) * W]))

        else:
            ans[i] = flatten_2[i * W:(i + 1) * W]
            ans[i].reverse()
            ans[i] = list(map(str, ans[i]))

    for i in range(H):
        print(" ".join(ans[i]))

Submission status: Accepted

Solution code:


def spaceinput():
    return list(map(int,input().split(" ")))

import numpy as np

H,W=spaceinput()
N=int(input())
a=spaceinput()

field=np.zeros([H,W])
k=0
for i in range(H):
    if i%2==0:
        for j in range(W):
            field[i][j]=k+1
            a[k]-=1
            if a[k]==0:
                k+=1

    else:
        for j in reversed(range(W)):
            field[i][j]=k+1
            a[k]-=1
            if a[k]==0:
                k+=1


for i in range(H):
    a=field[i]
    b=list(map(str,map(int,a.tolist())))
    #print(b)
    print(" ".join(b))

Submission status: Accepted

Solution code:
h,w=map(int,raw_input().split())
n=int(raw_input())
a=map(int,raw_input().split())
b=[[0]*2 for i in range(n+1)]
for i in range(1,n+1):
	b[i][0]=a[i-1]
	b[i][1]=i
b=sorted(b, key=lambda x: -x[0])
c=[[0 for i in range(w)] for i in range(h)]
x=y=0
for i in range(n):
	for j in range(b[i][0]):
		c[x][y]=b[i][1]
		if x%2==0:
			y+=1
		else:
			y-=1
		if y>=w:
			x+=1
			y-=1
		if y<0:
			x+=1
			y+=1
for i in range(h):
	for j in range(w):
		print c[i][j],
	print

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

H, W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))

a_list = []
for i in range(N):
    heappush(a_list, (a[i], i + 1))

c = [[0] * W for _ in range(H)]
remain = 0
for y in range(H):
    if y % 2 == 0:
        for x in range(W):
            if remain == 0:
                remain, num = heappop(a_list)
            c[y][x] = num
            remain -= 1
    else:
        for x in reversed(range(W)):
            if remain == 0:
                remain, num = heappop(a_list)
            c[y][x] = num
            remain -= 1

for row in c:
    s = ' '.join([str(i) for i in row])
    print(s)

Submission status: Accepted

Solution code:
def fill_left(k, y, x, a, ans):
    global cnt
    for j in xrange(x, w):
        ans[y][j] = k + 1
        cnt += 1
        if cnt == a[k]:
            return j
    return -1

def fill_right(k, y, x, a, ans):
    global cnt
    for j in xrange(x, -1, -1):
        ans[y][j] = k + 1
        cnt += 1
        if cnt == a[k]:
            return j
    return -1

h, w = map(int, raw_input().split())
n = int(raw_input())
a = map(int, raw_input().split())
ans = [[0] * w for _ in xrange(h)]
nowy = 0
nowx = 0
left = True
cnt = 0
k = 0
while nowy < h:
    if left:
        tmp = fill_left(k, nowy, nowx, a, ans)
        if tmp == -1:
            left = False
            nowx = w - 1
            nowy += 1
        else:
            if tmp == w - 1:
                left = False
                nowx = w - 1
                nowy += 1
                k += 1
                cnt = 0
            else:
                k += 1
                nowx = tmp + 1
                cnt = 0
    else:
        tmp = fill_right(k, nowy, nowx, a, ans)
        if tmp == -1:
            left = True
            nowx = 0
            nowy += 1
        else:
            if tmp == 0:
                left = True
                nowx = 0
                nowy += 1
                k += 1
                cnt = 0
            else:
                k += 1
                nowx = tmp - 1
                cnt = 0
for i in xrange(h):
    for j in xrange(w):
        print ans[i][j],
    print

Submission status: Accepted

Solution code:
[H,W]=[int(x) for x in raw_input().split()]
N=int(raw_input())
A=[int(x) for x in raw_input().split()]
B=[[0 for x in range(W)] for y in range(H)]
p=0
q=0
d=1
k=0
D=6
for i in range(1,N+1):
    for j in  range(A[i-1]):
        B[p][(q+k)*d]=i
        q+=1
        if q==W:
            p+=1
            q=0
            d*=-1
            k= not k
for i in range(H):
    print "".join([str(x).ljust(D) for x in B[i]])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
H, W = [int(n) for n in input().split()]
N = int(input())
A = [int(n) for n in input().split()]

list_ = []
for i, num in enumerate(A):
    list_.extend([i+1]*num)

result = ""
for h in range(H):
    tmp = [str(n) for n in list_[h*W:(h+1)*W]]
    if h%2==0:
        result += " ".join(tmp) + "\n"
    else:
        result += " ".join(tmp[::-1]) + "\n"
print(result[:-1])

Submission status: Accepted

Solution code:
H, W = map(int, raw_input().split())
N = int(raw_input())
A = map(int, raw_input().split())

X = []
for i, a in enumerate(A):
    X += [str(i+1)] * a

for h in range(H):
    if h % 2 == 0:
        print " ".join(X[W*h:W*(h+1)])
    else:
        print " ".join(X[W*h:W*(h+1)][::-1])

Submission status: Accepted

Solution code:
H,W=map(int,raw_input().split())
N=int,raw_input()
a=map(int,raw_input().split())
c=[[0 for i in range(W)] for i in range(H)]
num=0
count=0
d=1
x=0
y=0
s=0
while x<W:
    count+=1
    if a[num]+s<count:
        s+=a[num]
        num+=1
    c[y][x]=num+1
    y+=d
    if d==1 and y==H:
        x+=1
        d=-1
        y-=1
    if d==-1 and y==-1:
        x+=1
        d=1
        y+=1
for i in c:
    for j in i:
        print j,
    print

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
n = int(input())
d = list(map(int, input().split()))

c = []
for i in range(len(d)):
	for _ in range(d[i]):
		c.append(i+1)

for i in range(h):
	res = ""
	for j in range(w):
		if i % 2 == 0:
			res = res + str(c.pop()) + ' '
		else:
			res = str(c.pop()) + ' ' + res

	print(res)

Submission status: Accepted

Solution code:
# coding: utf-8
INF = 10 ** 20
MOD = 10 ** 9 + 7


def II(): return int(input())
def ILI(): return list(map(int, input().split()))


def read():
    H, W = ILI()
    N = II()
    a = ILI()
    return H, W, N, a


def solve(H, W, N, a):
    ans = [[None] * W for __ in range(H)] # [H][W]
    ind_a = 0
    a_count = 0
    color_a = list(range(1, N + 1))
    for h in range(H):
        if h % 2 == 0:
            for w in range(W):
                ans[h][w] = color_a[ind_a]
                a_count += 1
                if a_count == a[ind_a]:
                    ind_a += 1
                    a_count = 0
        else:
            for w in reversed(range(W)):
                ans[h][w] = color_a[ind_a]
                a_count += 1
                if a_count == a[ind_a]:
                    ind_a += 1
                    a_count = 0

    ans = [" ".join(map(str, ele)) for ele in ans]
    ans = "\n".join(ans)
    return ans


def main():
    params = read()
    print(solve(*params))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N=int(input())
a=list(map(int,input().split()))

b=[]
for i in range(N):
  b+=[i+1]*a[i]
ans=[0]*H
for i in range(H):
  if i%2==0:
    print(" ".join(map(str,b[i*W:(i+1)*W])))
  else:
    print(" ".join(map(str,b[(i+1)*W-1:(i)*W-1:-1])))

Submission status: Accepted

Solution code:
import sys

# sys.stdin = open('d1.in')


def read_int_list():
    return list(map(int, input().split()))


def read_int():
    return int(input())


def read_str_list():
    return input().split()


def read_str():
    return input()


def solve():
    h, w = read_int_list()
    n = read_int()
    a = read_int_list()
    c = [[0] * w for i in range(h)]
    color = [0] * (w * h)
    t = 0
    for k in range(n):
        for l in range(a[k]):
            color[t] = k + 1
            t += 1
    t = 0
    for i in range(h):
        if i % 2 == 1:
            for j in range(w):
                c[i][j] = color[t]
                t += 1
        else:
            for j in range(w - 1, -1, -1):
                c[i][j] = color[t]
                t += 1
    for i in range(h):
        for j in range(w):
            print(c[i][j], end='')
            end = ' '
            if j == w - 1:
                end = '\n'
            print(end=end)
    return 0


def main():
    res = solve()


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
n = int(input())
a = list(map(int, input().split()))

ans = [[0 for _ in range(w)] for _ in range(h)]

cnt = 0
for i in range(n):
    for j in range(a[i]):
        r = cnt // w
        c = (r % 2) * (w - 1) + (-1)**(r % 2) * (cnt % w)
        ans[r][c] = i + 1
        cnt += 1

for ls in ans:
    print(' '.join(list(map(str, ls))))

Submission status: Accepted

Solution code:
ri = lambda: map(int, raw_input().split())
def pi(a): print (' '.join(map(str, a)))

h, w = ri()
n = input()
a = ri()

g = [[i + 1] * x for i, x in enumerate(a)]
g = [x for l in g for x in l]

for i in xrange(h):
    l = g[i*w:i*w+w]
    if i & 1:
        l = l[::-1]
    pi(l)

Submission status: Accepted

Solution code:
# D
H, W = map(int, input().split())
N = int(input())
a_list = list(map(int, input().split()))

res = [[str(0) for j in range(W)] for i in range(H)]

i = 0
j = 0
ind = 1

for k in range(H*W):
    if i % 2 == 0:
        a_list[ind-1] -= 1
        res[i][j] = str(ind)
        j += 1
        if a_list[ind-1] == 0:
            ind += 1
        if j == W:
            j = W - 1
            i += 1
    else:
        a_list[ind-1] -= 1
        res[i][j] = str(ind)
        j -= 1
        if a_list[ind-1] == 0:
            ind += 1
        if j == -1:
            j = 0
            i += 1
        
for i in range(H):
    print(" ".join(res[i]))

Submission status: Accepted

Solution code:
h, w = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))
grid = [[' ']*w for i in range(h)]

ci = 0
for i in range(h):
    for j in range(w):
        if not a[ci]: ci+= 1
        if i%2==0: grid[i][j] = ci+1
        else: grid[i][~j] = ci+1
        a[ci]-= 1
for row in grid: print(*row)

Submission status: Accepted

Solution code:
def makelist(n, m):
	return [[0 for i in range(m)] for j in range(n)]

H, W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))

c = makelist(H, W)

y = 0
x = 0
vol = 1
for i in range(N):
	now = i + 1
	cnt = a[i]
	for k in range(cnt):
		c[y][x] = now
		if vol == 1:
			if x == W-1:
				y += 1
				vol = -vol
			else:
				x += vol
		elif vol == -1:
			if x == 0:
				y += 1
				vol = -vol
			else:
				x += vol
for y in range(H):
	for x in range(W):
		if x == 0:
			print(c[y][x], end="")
		else:
			print(" " + str(c[y][x]), end="")
	print()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
N = int(input())
A = list(map(int,input().split()))

ans = [[None]*W for _ in range(H)]

x,y = 0,0
d = 1
for c,a in enumerate(A):
  c += 1

  for i in range(a):
    if x < 0 or x >= W:
      y += 1
      d = -d
      x += d
    ans[y][x] = c
    x += d

for a in ans:
  print(' '.join(map(str,a)))

Submission status: Accepted

Solution code:
from itertools import chain

h, w = map(int, input().split())
n = int(input())
field = chain.from_iterable([i + 1] * a for i, a in enumerate(map(int, input().split())))
for r, row in enumerate(zip(*[field] * w)):
    if r & 1:
        print(*reversed(row))
    else:
        print(*row)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

H,W = map(int,input().split())
N = int(input())
a = [int(i) for i in input().split()]

grid = [list([None for i in range(W)]) for i in range(H)]

x = 0
y = 0
i = 0

d = 1
while i<N:
    grid[y][x] = i+1
    a[i]-=1
    if a[i]==0:
        i+=1

    x+=d
    
    if x==W:
        x-=1
        y+=1
        d= -1
        
    if x==-1:
        x+=1
        y+=1
        d = 1

for r in grid:
    print(" ".join([str(i) for i in r]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array
from bisect import *
from collections import *
import fractions
import heapq 
from itertools import *
import math
import re
import string

H, W = map(int, input().split())
N = int(input())
As = list(map(int, input().split()))

ret = []
r = []
for i, a in enumerate(As):
    while a > 0:
        if len(r) == W:
            ret.append(r)
            r = []
        r.append(i + 1)
        a -= 1
ret.append(r)

for i, r in enumerate(ret):
    if i % 2:
        print(*r[::-1])
    else:
        print(*r)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
A = [int(x) for x in input().split()]
board = [[0] * W for _ in range(H)]
colors = [i + 1 for i in range(N) for _ in range(A[i])]

for i in range(H):
    if i % 2 == 0:
        for j in range(W):
            board[i][j] = colors[i * W + j]
    else:
        for j in range(W):
            board[i][W-j-1] = colors[i * W + j]
for row in board:
    print(*row)

Submission status: Runtime Error

Solution code:
h,w,n,*A=map(int,open(x:=0).read().split());c=[]
for i in range(n):c+=[i+1]*A[i]
for i in range(h):print(*(c[i*w:-~i*w])[::x]);x^=1

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
n=int(input())
lst=[]

for i in range(1,n+1):
  for j in range(i):
    lst.append(str(i))
    
ans=[[0]*w for i in range(h)]

for i in range(h):
  if i%2==0:
    for j in range(w):
      ans[i][j]=lst.pop()

  else:
    for j in range(w-1,-1,-1):
      ans[i][j]=lst.pop()

for i in ans:
  print(' '.join(i))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
int res[110][110];
int main() {
	int n, h, w;
	cin >> h >> w >> n;
	int x = 0, y = w;
	for (int i = 1; i <= n; i++) {
		int a;
		cin >> a;
		y += 1;
		if (y == w + 1) {
			y = 1;
			x += 1;
		}
		for (int j = x; j <= h; j++) {
			bool ok = false;
			int t = (j == x ? y : 1);
			for (int k = t; k <= w; k++) {
				res[j][k] = i;
				a--;
				if (a == 0) {
					x = j;
					y = k;
					ok = true;
					break;
				}
			}
			if (ok) {
				break;
			}
		}
	}
	for (int i = 1; i <= h; i++) {
		if (i % 2 == 1) {
			for (int j = 1; j <= w; j++) {
				cout << res[i][j];
			}
		}
		else {
			for (int j = w; j >= 1; j--) {
				cout << res[i][j];
			}
		}
		cout << '\n';
	}

	return 0;
}

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())

N = int(input())

a = list(map(int,input().split()))

s = []

res = []

for v,i in enumerate(a,1):
    for _ in range(v):
        s.append(str(i))

for i in range(H):
    for j in range(W):
        res.append(str(s.pop(0)))
    if i % 2 == 1:
        res.reverse()
    print(' '.join(res))
    res = []

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
colors = [[i+1]*a[i] for i in n]
ans=[[0 for _ in range(w)] for _ in range(h)]
temp=0
for i in range(h):
    for j in range(w):
        if i%2==0:
            j = w-h-1
        ans[i][j]=colors[temp]
        temp+=1
        
for i in range(h):
    for j in range(2):
        print(ans[i][j], end="")
    print()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri Jun  5 09:50:00 2020

@author: NEC-PCuser
"""

H, W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))

gazo = [[0] * W  for i in range(H)]

count = 0
start_H = 0
start_W = 0
direction = 0
for i in range(len(a)):
    for j in range(a[i]):
        gazo[start_H][start_W] = i + 1
        if (start_W < W - 1 and direction == 0):
            start_W += 1
        elif (start_W == W - 1 and direction == 0):
            start_H += 1
            direction = 1
        elif (start_W > 0 and direction == 1):
            start_W -= 1
        elif (start_W == 0 and direction == 1):
            start_H += 1
            direction = 1

for i in range(len(gazo)):
    print(' '.join(map(str, gazo[i])))

Submission status: Runtime Error

Solution code:
#19 Grid Coloring
h,w=map(int,input().split() )
n=int(input())
a=list(map(int,input().split()))

import numpy as np

lis=[]
for i in range(n):
    lis.extend([i+1]*a[i])

lis = np.array(lis).reshape((h,w))

for i in range(1,h,2):
    lis[i] = lis[i][::-1]

for i in range(h):
    print(*lis[i])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    n=int(input())
    A=list(map(int,input().split()))
    val=max(A)
    val2=0
    minabs=10**10
    for i in range(n):
        if abs(A[i]-(val//2))<minabs:
            minabs=abs(A[i]-(val//2))
            val2=A[i]
    print(val,val2)    



    
resolve()

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
n = int(input())
a = list(map(int, input().split()))
field = [[0 for j in range(w)] for i in range(h)]
#[y, x]
d = [[0, 1], [1, 0], [0, -1], [-1, 0]]
y, x = 0, 0
for i in range(n):
    cnt = a[i]
    while cnt > 0:
        for j in range(len(d)):
            if 0 <= y + d[j][0] and y + d[j][0] < h and 0 <= x + d[j][1] and x + d[j][1] < w:
                if field[y+d[j][0]][x+d[j][1]] == 0: 
                    dy, dx = d[j][0], d[j][1]
                    break
        field[y][x] = i+1
        y += dy
        x += dx
        cnt -= 1
for i in range(h):
    for j in range(w):
        print(field[i][j], end=' ')
    print()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    H, W = map(int, input().split())
    n = int(input())
    A = list(map(int, input().split()))

    grid = [[0 for _ in range(W)] for _ in range(W)]
    h, w = 0, 0
    for i in range(n):
        cnt = A[i]
        while cnt:
            grid[h][w] = i + 1
            cnt -= 1
            if w + 1 < W:
                w += 1
            else:
                h += 1
                w = 0

    for h in range(H):
        print(*grid[h]) if h % 2 == 0 else print(*grid[h][::-1])


if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def pprint(c):
    for ci in c:
        print(*ci)

def main():
    h, w = MII()
    n = II()
    aa = MII()
    aa = deque([i+1 for i, a in enumerate(aa) for _ in range(a)])
    if w == 1:
        print(*aa, sep='\n')
        return None
    c = DD2(h,w)
    for i in range(h):
        for j in range(i,w-i): # to right
            c[i][j] = aa.popleft()
        if not aa:
            break
        for k in range(i+1, i+1+(h-2*(i+1))): # to down
            c[k][w-1-i] = aa.popleft()
        for j in reversed(range(i,w-i)): # to left
            c[h-1-i][j] = aa.popleft()
        for k in reversed(range(i+1, i+1+(h-2*(i+1)))): # to up
            c[k][i] = aa.popleft()
    for ci in c:
        print(*ci)



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def pprint(c):
    for ci in c:
        print(*ci)

def main():
    h, w = MII()
    n = II()
    aa = MII()
    aa = deque([i+1 for i, a in enumerate(aa) for _ in range(a)])
    c = DD2(h,w)
    for i in range(h):
        for j in range(i,w-i): # to right
            c[i][j] = aa.popleft()
        if not aa:
            break
        for k in range(i+1, i+1+(h-2*(i+1))): # to down
            c[k][w-1-i] = aa.popleft()
        for j in reversed(range(i,w-i)): # to left
            c[h-1-i][j] = aa.popleft()
        for k in reversed(range(i+1, i+1+(h-2*(i+1)))): # to up
            c[k][i] = aa.popleft()
    for ci in c:
        print(*ci)



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
h, w = map(int,input().split())
n = int(input())
a_l = list(map(int,input().split()))

ans = []
for _ in range(h):
    ans.append([0]*w)

direction = 0
posx = 0
posy = 0
for i in range(n):
    for j in range(a_l[i]):
        ans[posy][posx] = i+1
        if direction == 0:
            posx += 1
            if posx == w-1:
                direction = 1
        elif direction == 1:
            posy += 1
            direction = 2
        elif direction == 2:
            posx -= 1
            if posx == 0:
                direction = 3
        elif direction == 3:
            posy += 1
            direction = 0

for val in ans:
    print(' '.join(map(str,val)))

Submission status: Runtime Error

Solution code:
import sys


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(10 ** 9)


def main():
    H, W = map(int, input().split())
    N = int(input())
    A = list(map(int, input().split()))
    C = [[0 for _ in range(W)] for _ in range(H)]
    h = 0
    w = 0
    flag = True
    for i in range(N):
        a = A[i]
        if flag:
            if w == W:
                h += 1
                for j in range(a):
                    C[h][j] = i + 1
                w = a
            elif w + a <= W:
                for j in range(w, w + a):
                    C[h][j] = i + 1
                w += a
            else:
                b = W - w
                for j in range(w, W):
                    C[h][j] = i + 1
                h += 1
                for j in range(a - b):
                    C[h][W - j - 1] = i + 1
                flag = False
                w = W - (a - b)
        else:
            if w == 0:
                h += 1
                for j in range(a):
                    C[h][j] = i + 1
                w = a
                flag = True
            elif w - a >= 0:
                for j in range(w - a, a):
                    C[h][j] = i + 1
                w -= a
            else:
                for j in range(w):
                    C[h][j] = i + 1
                h += 1
                for j in range(a - w):
                    C[h][j] = i + 1
                flag = True
                w = a - w
    for i in range(H):
        print(*C[i], sep=" ")


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(10 ** 9)


def main():
    H, W = map(int, input().split())
    N = int(input())
    A = list(map(int, input().split()))
    C = [[0 for _ in range(W)] for _ in range(H)]
    h = 0
    w = 0
    flag = True
    for i in range(N):
        a = A[i]
        if flag:
            if w == W:
                h += 1
                for j in range(a):
                    C[h][j] = i + 1
                w = a
            elif w + a <= W:
                for j in range(w, w + a):
                    C[h][j] = i + 1
                w += a
            else:
                b = W - w
                for j in range(w, W):
                    C[h][j] = i + 1
                h += 1
                for j in range(a - b):
                    C[h][W - j - 1] = i + 1
                flag = False
                w = W - (a - b)
        else:
            if w == 0:
                h += 1
                for j in range(a):
                    C[h][j] = i + 1
            elif w - a >= 0:
                for j in range(w - a, a):
                    C[h][j] = i + 1
                w -= a
            else:
                for j in range(w):
                    C[h][j] = i + 1
                h += 1
                for j in range(a - w):
                    C[h][j] = i + 1
                flag = True
                w = a - w
    for i in range(H):
        print(*C[i], sep=" ")


if __name__ == "__main__":
    main()