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: Time Limit Exceeded

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

c = [[0] * w for _ in range(h)]
li = [[0,0]]
hw = [0,0]
dir = 'r'

while len(li) < h*w:
    if dir == 'r':
        if hw[1] < h-1:
            if [hw[0], hw[1]+1] not in li:
                hw[1] += 1
            else:
                dir = 'd'
        else:
            dir = 'd'
    elif dir == 'd':
        if hw[0] < w-1:
            if [hw[0]+1, hw[1]] not in li:
                hw[0] += 1
            else:
                dir = 'l'
        else:
            dir = 'l'
    elif dir == 'l':
        if hw[1] > 0:
            if [hw[0], hw[1]-1] not in li:
                hw[1] -= 1
            else:
                dir = 'u'
        else:
            dir = 'u'
    else:
        if hw[0] > 0:
            if [hw[0]-1, hw[1]] not in li:
                hw[0] -= 1
            else:
                dir = 'r'
        else:
            dir = 'r'
    if hw not in li:
        li.append([hw[0], hw[1]])

count = 0

for i in range(n):
    for _ in range(a[i]):
        c[li[count][1]][li[count][0]] = i+1
        count += 1

for i in range(h):
    for j in range(w):
        print(c[i][j],end = ' ')
    print()

Submission status: Time Limit Exceeded

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 = {}
    for i in range(N):
        color_num_list[i+1] = (int(input_raw[i]))

    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)
        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: Memory Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())


H, W = MI()
N = II()
a = LI()
color = deque()
ans = [[0] * W for _ in range(H)]
# visited = [[0] * W for _ in range(H)]
x_diff = [-1, 0, 1, 0]
y_diff = [0, 1, 0, -1]

for i, num in enumerate(a):
    for j in range(num):
        color.append(i + 1)

# coordinate_q = deque()
# coordinate_q.append([0, 0])
# visited[0][0] = 1
# ans[0][0] = color.popleft()

"""
while len(coordinate_q) != 0:
    y_tmp, x_tmp = coordinate_q.popleft()
    for i in range(4):
        y, x = y_tmp + y_diff[i], x_tmp + x_diff[i]
        if 0 <= y <= H-1 and 0 <= x <= W-1 and visited[y][x] == 0:
            ans[y][x] = color.popleft()
            visited[y][x] = 1
            coordinate_q.append([y, x])
"""

"""
for i in range(H):
    for j in range(W):
        if i % 2 == 0:
            ans[i][j] = color.popleft()
        else:
            ans[i][-(j+1)] = color.popleft()
"""

def tansaku(y, x):
    if visited[y][x] == 1:
        return
    visited[y][x] = 1
    ans[y][x] = color.popleft()
    for i in range(4):
        ny = y + y_diff[i]
        nx = x + x_diff[i]
        if 0 <= ny <= H-1 and 0 <= nx <= W-1:
            tansaku(ny, nx)

visited = [[0] * W for _ in range(H)]
tansaku(0, 0)

for i in range(H):
    for j in range(W):
        print(ans[i][j], end=' ')
    print('')

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
A = list(map(int, input().split()))
tiles = [[0 for _ in range(W)] for _ in range(H)]
index = 0
rest_a = A[0]
for h in range(H):
  for w in range(W):
    if rest_a == 0:
      index += 1
      rest_a = A[index]-1
    else:
      rest_a -= 1
    if h%2 == 0:
      tiles[h][w] = index+1
    else:
      tiles[h][W-w-1] = index+1
for h in range(H):
  print(' '.join(map(str, tiles[h])))

Submission status: Accepted

Solution code:
import sys


def main():
    h, w = map(int, sys.stdin.buffer.readline().split())
    n = int(sys.stdin.buffer.readline())
    a = list(map(int, sys.stdin.buffer.readline().split()))
    ans = [0]*(w*h)
    now = 0
    for i, x in enumerate(a):
        for j in range(x):
            ans[now + j] = i+1
        now += x

    for i in range(h):
        if i % 2:
            print(*reversed(ans[i*w:(i+1)*w]))
        else:
            print(*ans[i*w:(i+1)*w])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np


def main():
    h, w = map(int, sys.stdin.buffer.readline().split())
    n = int(sys.stdin.buffer.readline())
    a = list(map(int, sys.stdin.buffer.readline().split()))
    ans = np.zeros(w*h, np.int64)
    now = 0
    for i, x in enumerate(a):
        for j in range(x):
            ans[now + j] = i+1
        now += x

    ans = ans.reshape(h, w)
    for i in range(h):
        if i % 2:
            print(*ans[i, ::-1])
        else:
            print(*ans[i])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W,N,*a=map(int,open(0).read().split())
O=[]
for i in range(N):O+=[i+1]*a[i]
for i in range(H):print(*O[W*i:W*-~i][::(-1)**i])

Submission status: Accepted

Solution code:
H,W,N,*a=map(int,open(0).read().split())
O=[[0]*W for _ in range(H)]
i=0
for j in range(N):
 for k in range(a[j]):w=i%W if i//W%2 else W-1-i%W;O[i//W][w]=str(j+1);i+=1
for i in range(H):print(' '.join(O[i]))

Submission status: Accepted

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

ans=[]
for i in range(N):
    for j in range(A[i]):
        ans.append(i+1)

for y in range(H):
    x=ans[y*W:y*W+W]
    if y%2!=0:
        x.reverse()
    print(*x)

Submission status: Accepted

Solution code:
h,w,n,*A=map(int,open(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][::(-1)**i])

Submission status: Accepted

Solution code:
h,w,n,*A=map(int,open(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:][::(-1)**i])

Submission status: Accepted

Solution code:
h,w,n,*A=map(int,open(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])[::(-1)**i])

Submission status: Accepted

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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
tmp=[]
for i in range(len(a)):
  for _ in range(a[i]):
    tmp.append(i+1)
ans=[]
for i in range(h):
  if i%2==0:
    print(*tmp[i*w:i*w+w])
  else:
    print(*list(reversed(tmp[i*w:i*w+w])))

Submission status: Accepted

Solution code:
H,W=list(map(int, input().split()))
N=int(input())
A=list(map(int, input().split()))
L=[0]*(H*W)
n=0
for i in range(N):
  a=A[i]
  L[n:n+a]=[i+1]*a
  n+=a
for i in range(H):
  S=L[i*W:(i+1)*W]
  if i%2==1:
    S=S[::-1]
  print(*S)

Submission status: Accepted

Solution code:
h, w = (int(x) for x in input().split())
n = int(input())
A = list(int(x) for x in input().split())
B = []
for i, a in enumerate(A, start=1):
    B += [i] * a
for i in range(h):
    start, end = i * w, i * w + w
    if i % 2 == 0:
        print(*B[start:end])
    else:
        print(*B[start:end][::-1])

Submission status: Accepted

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

for i in range(N):
    ans_lis = ans_lis + [i + 1] * a[i]

for i in range(H):

    if i % 2 == 0:
        k = 1
    else:
        k = -1

    ans = ans_lis[i * W:(i + 1) * W][::k]
    ans = list(map(str, ans))
    print(" ".join(ans))

Submission status: Accepted

Solution code:
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():


    h, w = LI()
    n = I()
    a = [0] + LI()

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


    zahyo = [0,0]
    pr = True
    for color in range(1, len(a)):
        for i in range(a[color]):
            board[zahyo[0]][zahyo[1]] = color
            if pr:
                if zahyo[1] == w-1:
                    zahyo[0] += 1
                    pr = False
                else:
                    zahyo[1] += 1
            else:
                if zahyo[1] == 0:
                    zahyo[0] += 1
                    pr = True
                else:
                    zahyo[1] -= 1


    for line in board:
        print(*line)
            


                    


main()

Submission status: Accepted

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

ans = []
for i, a in enumerate(A):
  index = i + 1
  for _ in range(a):
    ans.append(index)
  
m = [[0 for _ in range(w)] for _ in range(h)]
cnt = 0
for i in range(h):
  if i % 2 == 0:
    for j in range(w):
      m[i][j] = ans[cnt]
      cnt += 1
  else:
    for j in range(w-1,-1,-1):
      m[i][j] = ans[cnt]
      cnt += 1
  print(" ".join(map(str, m[i])))

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]

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

Submission status: Accepted

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

g = [[0]*W for i in range(H)]
h = 0
w = 0
for i in range(N):
  for j in range(a[i]):
    g[h][w] = i+1
    if h % 2 == 0:
      if w == (W-1):
        h += 1
      else:
        w += 1
    else:
      if w == 0:
        h += 1
      else:
        w -= 1
        
for i in range(H):
  for j in range(W):
    print(g[i][j], end=" ")
  print("")

Submission status: Accepted

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

li = []
for i in range(n):
    for j in range(L[i]):
        li.append((i+1))
#print(L,li)
l = h*w-len(li)
li = li + [0]*l
ans = []
for i in range(h):
    ans.append(li[i*w:(i+1)*w])

for i in range(h-1):
    if ans[i][-1] == ans[i+1][0]:
        ans[i+1] = ans[i+1][::-1]
#print(ans)
for i in range(h):
    print(*ans[i])

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    return C

H,W=mint()
N=intput()
A=[0]+lint()
C=[[0]*W for _ in range(H)]
k=1
a=0
for i in range(H):
    tmp = range(W) if i%2==0 else range(W-1,-1,-1)
    for j in tmp:
        C[i][j]=k
        a+=1
        if a==A[k]:
            k+=1
            a=0
for c in C:
    lprint(c,' ')
    print('')

Submission status: Accepted

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

color_row = []
for i,a in enumerate(A):
    color_row += [i+1 for _ in range(a)]


for i in range(h):
    if i%2 == 0:
        print(*color_row[w*i:w*i+w])
    else:
        print(*reversed(color_row[w*i:w*i+w]))

Submission status: Accepted

Solution code:
h, w = list(map(int, input().split()))
n = int(input())
colors = list(map(int, input().split()))
ans = [[0] * w for i in range(h)]
color_stock = []
for i in range(len(colors)):
    for j in range(colors[i]):
        color_stock.append(i+1)


for i in range(h):
    if i % 2 == 0:
        for j in range(w):
            c = color_stock.pop()
            ans[i][j] = c
    else:
        for j in range(w, 0, -1):
            c = color_stock.pop()
            ans[i][j-1] = c

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

Submission status: Accepted

Solution code:
'''
Created on 2020/09/04

@author: harurun
'''
def main():
  import sys
  pin=sys.stdin.readline
  pout=sys.stdout.write
  perr=sys.stderr.write

  H,W=map(int,pin().split())
  N=int(pin())
  a=list(map(int,pin().split()))
  l=[]
  for i in range(N):
    l+=[str(i+1) for _ in range(a[i])]
  s=1
  ans=[]
  for j in range(H):
    if s==1:
      ans=list(l[j*W:(j+1)*W])
      s=-1
    else:
      ans=list(l[j*W:(j+1)*W])
      ans.reverse()
      s=1
    u=" ".join(ans)
    print(u)
  return 
main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N = int(input())
Alist = list(map(int,input().split()))
C = [[0]*W for _ in range(H)]
def change(x,y):
    return (-y,x)
h = 0
w = 0
(x,y) = (1,0)
i = 1
for a in Alist:
    while a > 0:
        C[h][w] = i
        h += y
        w += x
        a -= 1
        if w == W or h == H or w == -1 or h == -1 or C[h][w] != 0:
            h -= y
            w -= x
            (x,y) =change(x,y)
            h += y
            w += x
    i += 1
for c in C:
    print(*c)

Submission status: Accepted

Solution code:
def main():
    h,w=map(int,input().split())
    n=int(input())
    a=list(map(int,input().split()))
    ans=[[0]*w for _ in range(h)]
    x,y=0,0
    r=False
    for i,v in enumerate(a):
        i+=1
        while v > 0:
            #print("x:{} y:{} = {}".format(x,y,i))
            ans[y][x] = i
            v -= 1
            x = x-1 if r else x+1
            if x < 0 or w <= x:
                r=not r
                x = w-1 if r else 0
                y+=1
    for i in ans:
        print(*i)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
r, c = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))

x = 0
grid = [[] for i in range(r)]
for i in range(r):
    while x < n and len(grid[i])+a[x] <= c:
        grid[i].extend([x+1]*a[x])
        x += 1
    if x < n:
        a[x] -= c-len(grid[i])
        grid[i].extend([x+1]*(c-len(grid[i])))

for i in range(1,r,2):
    grid[i] = grid[i][::-1]

for row in grid:
    print(*row)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
n = int(input())
a = list(map(int, input().split()))
ans = [[0] * w for _ in range(h)]
now_color = 1
now_a_index = now_color - 1
ans_index = [0, 0]
for i in range(h * w):
    ans[ans_index[0]][ans_index[1]] = now_color
    a[now_a_index] -= 1
    if a[now_a_index] == 0:
        now_color += 1
        now_a_index += 1
    ans_index[1] += 1
    if ans_index[1] >= w:
        ans_index[1] = 0
        ans_index[0] += 1
cnt = 0
for l_ans in ans:
    if cnt % 2 == 1:
        for ll_ans in reversed(l_ans):
            print(ll_ans, end=" ")
        cnt += 1
    else:
        for ll_ans in l_ans:
            print(ll_ans, end=" ")
        cnt += 1
    print("")

Submission status: Accepted

Solution code:
# 囲いを作らないように端から順に塗っていけばよい
# あとはマス目をどう管理するか
h,w = list(map(int, input().split()))
n = int(input())
a = [0] + list(map(int, input().split()))[::-1]
b = [[0] * w for _ in range(h)]
color = 1
rest = a.pop()
for x in range(w):
    if x&1:
        hh = reversed(range(h))
    else:
        hh = range(h)
        
    for y in hh:
        b[y][x] = color
        rest -= 1
        if rest == 0:
            color += 1
            rest= a.pop()

for line in b:
    print(*line)

Submission status: Accepted

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

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

cur = 1
cnt = 0
for y in range(h):
    for x in range(w):
        if y % 2 == 0:
            g[y][x] = cur
        else:
            g[y][w-x-1] = cur

        cnt += 1
        if a[cur-1] == cnt:
            cnt = 0
            cur += 1


for row in g:
    print(" ".join(map(str, row)))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N=int(input())
a=list(map(int,input().split()))
answers=[[0 for _ in range(W)] for _ in range(H)]
h=0
w=0
number=1
for a_ in a:
    for _ in range(a_):
        answers[h][w] = number
        if w>=0:
            w+=1
        else:
            w-=1
        if w==W:
            h+=1
            w=-1
        elif w==-W-1:
            h+=1
            w=0
    number+=1
for answer in answers:
    print(*answer)

Submission status: Accepted

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

b = queue.Queue()
for i, j in enumerate(a):
    for _ in range(j):
        b.put(i+1)

for i in range(h):
    ans = []
    for j in range(w):
        ans += [b.get()]
    if i%2 == 1:
        ans = list(reversed(ans))
    print(*ans)

Submission status: Accepted

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


for i in range(1,n+1):
  for j in range(a[i-1]):
    lst.append(str(i))

lst.reverse()
    
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: Accepted

Solution code:
def main():
    h,w = map(int,input().split())
    n = int(input())
    a = list(map(int,input().split()))
    c = [[0 for i in range(w)] for i in range(h)]
    p = [0,0]
    up = 1
    for i in range(n):
        cnt = 0
        while cnt<a[i]:
            c[p[0]][p[1]] = i+1
            cnt += 1
            if up==1 and p[1] < w-1:
                p[1] += 1
            elif up == 1 and p[1] == w-1:
                p[1] = w-1
                p[0] += 1
                up = 0
            elif up == 0 and p[1] > 0:
                p[1] -= 1
            elif up == 0 and p[1] == 0:
                p[1] = 0
                p[0] += 1
                up = 1
    for i in range(h):
        print(' '.join([str(x) for x in c[i]]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

# input = stdin.readline

def solve(h,w,n,a):
  acc = []
  for i in range(n):
    acc.extend([i+1]*a[i])
  res = []
  k = 0
  for i in range(h):
    res.append(acc[k:k+w] if i%2==0 else acc[k:k+w][::-1])
    k += w
  return res


def main():
  H,W = map(int,input().split())
  N = int(input())
  a = list(map(int,input().split()))
  ans = solve(H,W,N,a)
  for i in range(H):
    print(*ans[i])
  




if __name__ == '__main__':
  main()

Submission status: Accepted

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

for i in range(n):
  while a[i]>0:
    a[i] -=1
    c.append(str(i+1))

for i in range(h):
  if i%2==0:
    print(" ".join(c[i * w:(i + 1) * w]))
  else:
    print(" ".join(reversed(c[i * w:(i + 1) * w])))

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import collections
from collections import deque
from collections import defaultdict

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
MOD2 = 998244353
input = lambda: sys.stdin.readline().strip()

NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()

def main():

    H,W = NMI()
    N = NI()
    A = NLI()
    
    ls = []
    
    
    for n in range(N):
        for _ in range(A[n]):
            ls.append(n+1)
    
    
    for h in range(H):
        if h % 2 == 0:
            print(" ".join(map(str,ls[h*W:(h+1)*W])))
        else:
            print(" ".join(map(str,list(reversed(ls[h*W:(h+1)*W])))))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))

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


def main():
    H, W = MAP()
    N = INT()
    A = LIST()

    idx = 0
    cnt = 0
    C = [[0] * W for _ in range(H)]
    for i in range(H):
        for j in range(W):
            C[i][j] = idx + 1
            cnt += 1
            if A[idx] == cnt:
                idx += 1
                cnt = 0

    for i in range(H):
        line = list(reversed(C[i])) if i % 2 else C[i]
        print(*line)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
import numpy as np
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
N = INT()
A = LIST()

ans = []
for i in range(N):
    tmp = [i+1] * A[i]
    ans += tmp

ans = np.array(ans).reshape(H, W).tolist()
for i in range(H):
    if i % 2 == 1:
        ans[i] = ans[i][::-1]

for a in ans:
    print(' '.join([str(i) for i in a]))

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_left, bisect_right

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
N = INT()
A = LIST()
C = [[0] * W for i in range(H)]
i = 0
for h in range(H):
    for w in range(W):
        while A[i] == 0:
            i += 1
        if h % 2 == 0:
            # forward
            C[h][w] = i + 1
        else:
            # backward
            C[h][W-w-1] = i + 1
        A[i] -= 1
# print(*[c for c in C], sep="\n")
for c in C:
    print(*c, sep=" ")

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
A=list(map(int,input().split()))
q=[]
for i in range(n):
  q+=[i+1]*A[i]
c=[[0]*w for _ in range(h)]
for i in range(h):
  if i%2==0:
    for j in range(w):
      c[i][j]=q.pop(0)
  else:
    for j in range(w-1,-1,-1):
      c[i][j]=q.pop(0)

for i in c:
  print(' '.join(map(str, i)))

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    H, W = map(int, readline().split())
    N = int(readline())
    A = list(map(int, readline().split()))
    C = [[0]*W for _ in range(H)]
    h=0
    w=0
    for i,a in enumerate(A):
        for _ in range(a):
            C[h][w] = i +1
            w += 1
            if w==W:
                h += 1
                w = 0
    for i,c in enumerate(C):
        if i%2==0:
            print(' '.join(map(str, c)))
        else:
            print(' '.join(map(str, reversed(c))))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
A = list(map(int, input().split()))
C = [[0] * W for _ in range(H)]
x = -1
for c, i in enumerate(A, 1):
  for _ in range(i):
    x += 1
    row = x // W
    column = x % W
    C[row][column] = c
for i in range(H):
  if i%2 == 0:
    print(*C[i])
  else:
    print(*C[i][::-1])

Submission status: Accepted

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

N = int(input())

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

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

strate = True
w = 0
h = 0
dp[0][0] = 1

for key,value in enumerate(a):
    if key == 0:
        count = 1
        if value == 1:
            continue       
    else:
        count = 0

    while count < value:
        count += 1
        if strate:
            if w < W-1:
                w += 1
            elif w == W-1:
                strate = False
                h += 1
        else:
            if 0 < w:
                w -= 1
            elif w == 0:
                strate = True
                h += 1

        dp[h][w] = key+1
                
for aa in dp:
    print(*aa)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
N = int(input())
A = list(map(int,input().split()))
A.insert(0,0)
B = [[0 for _ in range(W)] for _ in range(H)]

col = 1
cnt = 0
i = 0
j = 0
d = 1
while True:
    if cnt<A[col]:
        B[i][j] = col
        cnt += 1
    else:
        col += 1
        cnt = 0
        B[i][j] = col
        cnt += 1
    if d==1 and j<W-1:
        j += 1
    elif d==1 and j==W-1:
        i += 1
        d = -1
    elif d==-1 and j>0:
        j -= 1
    elif d==-1 and j==0:
        i += 1
        d = 1
    if i>=H:break
for i in range(H):
    print(*B[i])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


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)]
    k = 0

    for j in range(h):
        if j % 2 == 0:
            for i in range(w):
                c[j][i] = k + 1
                a[k] -= 1

                if a[k] == 0:
                    k += 1
        else:
            for i in range(w - 1, -1, -1):
                c[j][i] = k + 1
                a[k] -= 1

                if a[k] == 0:
                    k += 1

    for ci in c:
        print(' '.join(map(str, ci)))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

h = 0
w = 0
num = 1

for i in range(N):
    while A[i] > 0:
        MAP[h][w] = num
        A[i] -= 1
        if h % 2 == 0:
            if w == W - 1:
                h += 1
            else:
                w += 1
        else:
            if w == 0:
                h += 1
            else:
                w -= 1
    num += 1

for i in range(H):
    print(*MAP[i])