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:
h, w = map(int, input().split())
n = int(input())
a = list(map(int, input().split()))
c = []
for i in range(n):
    c += [i+1]*a[i]
ans = []
for h_ in range(h):
    a = c[h_*w: w+h_*w]
    if h_ % 2 == 0:
        ans.append(a)
    else:
        ans.append(a[::-1])
for i in ans:
    print(*i)

Submission status: Accepted

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

import numpy as np
res = np.zeros(H*W,dtype=np.int64)

pos = 0
for i in range(N):
    color = i+1
    for j in range(A[i]):
        res[pos+j] = color
    pos += A[i]
res = np.reshape(res,(H,W))
for i in range(H):
    if i%2 == 0:
        pass
    else:
        res[i] = res[i][::-1]
#print(res)

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

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N=int(input())
l=list(map(int,input().split()))
l2=[]
lt=[]
a=1
for x in l:
  for i in range(x):
    if len(lt)>=W:
      if len(l2)%2==1:
        lt.reverse()
        l2.append(lt)
      else:
        l2.append(lt)
      lt=[][:]
      lt.append(a)
    else:
      lt.append(a)
  a+=1
if len(lt)>0:
  if len(l2)%2==1:
    lt.reverse()
    l2.append(lt)
  else:
    l2.append(lt)
for x in l2:
  print(' '.join([str(a) for a in x]))

Submission status: Accepted

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


def solve(H: int, W: int, N: int, a: "List[int]"):
    S = []
    for i, n in enumerate(a):
        j = i + 1
        S.extend([j] *  n)
    
    for h in range(H):
        row = S[h*W:h*W+W]
        if h % 2 == 0:
            print(' '.join(map(str, row)))
        else:
            print(' '.join(map(str, row[::-1])))

    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    N = int(next(tokens))  # type: int
    a = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(H, W, N, a)

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 n in range(N):
    c += [n+1]*a[n]
ans = []
for h in range(H):
    a = c[h*W:W+h*W]
    if h%2==0: ans.append(a)
    else: ans.append(a[::-1])
for i in ans:
    print(*i)

Submission status: Accepted

Solution code:
import numpy as np

h, w = map(int, input().split())
N = int(input())
a = np.array(list(map(int, input().split())))

x = np.argsort(a)
x = x[::-1]
a = a[x]

tmp = np.zeros(h*w)

k = 0
for i in range(N):
    for j in range(a[i]):
        tmp[k] = x[i]+1
        k += 1

tmp = tmp.reshape((h,w))

for y in range(h):
    if y&1 == 0:
        for x in range(w):
            print(int(tmp[y][x]), end=" ")
        print()
    else:
        for x in range(w-1, -1, -1):
            print(int(tmp[y][x]), end=" ")
        print()

Submission status: Accepted

Solution code:
H, W = map(int,input().split())
N = int(input())
a = list(map(int,input().split()))
c = [[None for _ in range(W)] for _ in range(H)]
cur = 1
for i in range(H):
    if i % 2 == 0:
        for j in range(W):
            a[cur-1] -= 1
            c[i][j] = cur
            if a[cur-1] == 0:
                cur += 1
    else:
        for j in range(W-1, -1, -1):
            a[cur-1] -= 1
            c[i][j] = cur
            if a[cur-1] == 0:
                cur += 1
for i in range(H):
    print(" ".join(map(str, c[i])))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N=int(input())
A=list(map(int,input().split()))
a=[[0]*W for i in range(H)]
r,c=0,0
x=1
for i in range(H*W):
    a[r][c]=x
    A[x-1]-=1
    if A[x-1]==0:
        x+=1
    if (r%2==0 and c==W-1 or r%2==1 and c==0) and r<H-1:
        r+=1
    elif r%2==0:
        c+=1
    else:
        c-=1
for l in a:
    print(' '.join(map(str,l)))

Submission status: Accepted

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

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

ans = [0] * (H * W)

index = 0

for color , a in enumerate(A) :
    for _ in range(a) :
        ans[index] = color + 1
        index += 1

for i in range(H) :
    sub = ans[i * W : (i + 1) * W]
    if i % 2 == 0 :
        for j in range(W) :
            print('{} '.format(sub[j]), end='')
    else :
        sub.reverse()
        for j in range(W) :
            print('{} '.format(sub[j]), end='')
    print('')

Submission status: Accepted

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

c = []
idx = 0
jdx = 0

for i, cnt in enumerate(a):
    i += 1
    for _ in range(cnt):
        #print(i,cnt,c,idx,jdx)
        if jdx%2 == 0:
            if idx < W:
                c += [i]
                idx += 1
            else:
                print(*c)
                c = [i]
                idx -= 1
                jdx += 1
        else:
            if idx > 0:
                c = [i] + c
                idx -=  1
            else:
                print(*c)
                c = [i]
                idx += 1
                jdx += 1

print(*c)

Submission status: Accepted

Solution code:
from functools import *

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

ans_list = ([[i+1] * a[i] for i in range(N)])
ans_list = reduce(lambda a, b: a + b, ans_list)

for i in range(H):
    ans = ans_list[i*W:i*W+W] if i%2 == 0 else ans_list[i*W+W-1:i*W-1:-1]
    print(*ans)

Submission status: Accepted

Solution code:
import math

H,W = [int(x) for x in input().split()]
N = int(input())
a = [int(x) for x in input().split()]
li = []
for ind,i in enumerate(a):
    for j in range(i):
        li.append(ind+1)
prt = ''
for ind,i in enumerate(li):
    if(math.floor(ind/W)%2 == 0):
        prt+=str(i)+' '
        if(ind%W==W-1):
            prt=prt[:-1]
            print(prt)
            prt=''
    else:
        prt=' '+str(i)+prt
        if(ind%W==W-1):
            prt=prt[1:]
            print(prt)
            prt=''

Submission status: Accepted

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

stage = [[0 for _ in range(W)] for _ in range(H)]
ds = ((0, 1), (1, 0), (0, -1), (-1, 0))

def set_val(p, v):
	global stage
	stage[p[0]][p[1]] = v

def get_val(p):
	return stage[p[0]][p[1]]

current_p = [0, 0]
set_val(current_p, 1)
A[0] -= 1

for i, a in enumerate(A):
	n = a
	while 0 < n:
		for d in ds:
			next_p = (current_p[0] + d[0], current_p[1] + d[1])
			if 0 <= next_p[0] < H and 0 <= next_p[1] < W:
				v = get_val(next_p)
				if v == 0:
					set_val(next_p, i + 1)
					current_p = next_p
					break
		n -= 1

for line in stage:
	print(*line)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
arr=list(map(int,input().split()))
ans=[[0]*w for _ in range(h)]
hpos=0
wpos=0
apos=0
cnt=0
while 1:
  while cnt<arr[apos]:
    ans[hpos][wpos]=apos+1
    if hpos%2==0:
      wpos+=1
      if wpos==w:
        hpos+=1
        wpos=w-1
    else:
      wpos-=1
      if wpos==-1:
        hpos+=1
        wpos=0
    cnt+=1
  cnt=0
  apos+=1
  if hpos==h:
    break
for i in range(h):
  print(*ans[i])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
m=[[0 for _ in range(w)] for _ in range(h)]
c=0
for y in range(h):
    for x in range(w):
        if y%2==0:
            m[y][x]=c+1
            a[c]-=1
        else:
            m[y][w-1-x]=c+1
            a[c]-=1
        if a[c]==0:
            c+=1
for v in range(h):
    s=str(m[v][0])
    for u in range(1,w):
        s+=" "+str(m[v][u])
    print(s)

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 _ in range(a[i]):
        ans.append(i+1)
for i in range(H):
    if i % 2:
        print(*(list(reversed(ans[i * W:(i + 1) * W]))))
    else:
        print(*ans[i * W:(i + 1) * W])

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)]


c = 0
cnt_c = 0
for i in range(h):
  for j in range(w):
    if i % 2 == 0:
      ans[i][j] = str(c+1)
      
    else:
      ans[i][(w-1)-j] = str(c+1)
      
    cnt_c += 1
    if cnt_c == a[c]:
      c += 1
      cnt_c = 0
    
for i in range(h):
  print(" ".join(ans[i]))

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

h,w = li()
n = ni()
a = list(li())

grid = [[0]*w for _ in range(h)]
cnt = 0
for i, ai in enumerate(a):
    for _ in range(ai):
        grid[cnt//w][cnt%w] = i+1
        cnt += 1

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

Submission status: Accepted

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

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

co=0
for i in range(n):
    for j in range(a[i]):
        if (co//w)%2==1:
            ans[co//w][w-1-co%w]=i+1
        else:
            ans[co//w][co%w]=i+1
        co+=1
for i in range(h):
    for j in range(w-1):     
        print(ans[i][j],end=" ")
    print(ans[i][w-1])

Submission status: Accepted

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

i = 0
buf = [0] * W
k = 1
for x, ai in zip(range(1, N+1), map(int, input().split())):
  for _ in range(ai):
    buf[i] = x
    i += 1
    if i >= W:
      print(" ".join(map(str, buf[::k])))
      i = 0
      k = -k

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
A = [int(i) for i in input().split()]

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

cnt = 1
cnt2 = 0
for h in range(H):
    if h % 2 == 0:
        for w in range(W):
            L[h][w] = cnt
            cnt2 += 1
            if cnt2 == A[cnt-1]:
                cnt += 1
                cnt2 = 0
            
    else:
        for w in range(W)[::-1]:
            L[h][w] = cnt
            cnt2 += 1
            if cnt2 == A[cnt-1]:
                cnt += 1
                cnt2 = 0
for h in range(H):
    print(*L[h])

Submission status: Accepted

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

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

for i in range(H):
    row = ""
    for j in range(W):
        r = W*i
        if i % 2 == 0:
            c = j
        else:
            c = W - 1 - j
        row += str(res[r+c])
        row += " "
    print(row)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
N = int(input())
a = list(map(int,input().split()))
import math
d = [[0] * W for _ in range(H)]

aidx = 0
didx = 0

while didx < H*W:
    idx = 0
    while idx < a[aidx]:
        d1 = math.ceil((didx+1)/W)-1
        if d1 % 2 == 1:
            d2 = W - 1 - didx % W
        else:
            d2 = didx % W
        d[d1][d2] = aidx+1
        idx += 1
        didx += 1
    aidx += 1
    
for i in range(H):
    print(' '.join(map(str,d[i])))

Submission status: Accepted

Solution code:
from itertools import cycle, chain, repeat

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

# (1, 1), (1, 2), ..., (1, W), (2, W), (2, W - 1), ..., (2, 2), (2, 1),
# (3, 1), (3, 2), ... の順で色1(1マス目), 色1(2マス目), ..., 色1(a_1マス目),
# 色2(1マス目), ..., 色2(a_2マス目), 色3(1マス目), ... と塗る
c = {
    (i, j): k
    for k, i, j in zip(
        chain(
            *(
                repeat(k, m)
                for k, m in enumerate(a, 1)
            )
        ),
        chain(
            *(
                repeat(r, W)
                for r in range(H)
            )
        ),
        cycle(
            chain(
                range(W),
                reversed(range(W)),
            )
        )
    )
}
ans = '\n'.join(
    ' '.join(
        str(c[(i, j)])
        for j in range(W)
    )
    for i in range(H)
)

# 出力
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate, cycle, chain, repeat
from bisect import bisect

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

# (1, 1), (1, 2), ..., (1, W), (2, W), (2, W - 1), ..., (2, 2), (2, 1),
# (3, 1), (3, 2), ... の順で色1(1マス目), 色1(2マス目), ..., 色1(a_1マス目),
# 色2(1マス目), ..., 色2(a_2マス目), 色3(1マス目), ... と塗る
A = list(accumulate(a))
c = {
    (i, j): bisect(A, k) + 1
    for k, i, j in zip(
        range(H * W),
        chain(
            *(
                repeat(r, W)
                for r in range(H)
            )
        ),
        cycle(
            chain(
                range(W),
                reversed(range(W)),
            )
        )
    )
}
ans = '\n'.join(
    ' '.join(
        str(c[(i, j)])
        for j in range(W)
    )
    for i in range(H)
)

# 出力
print(ans)

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):
    ans+=[str(i+1)]*a
for h in range(H):
    if h%2==0:
        print(" ".join(ans[h*W:(h+1)*W]))
    else:
        print(" ".join(ans[h*W:(h+1)*W][::-1]))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
A=[int(i) for i in input().split()]
AA=[]
for i in range(n):
  ai=A[i]
  for j in range(ai):
    AA.append(i+1)
for i in range(h):
  AAA=AA[i*w:(i+1)*w]
  if i%2!=0:
    AAA=AAA[::-1]
  print(*AAA)

Submission status: Accepted

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

c = [[0]*W for i in range(H)]
x = 0
y = 0
for i in range(N):
    for j in range(A[i]):
        c[y][x] = i+1
        if y % 2:
            if x == 0:
                y += 1
            else:
                x -= 1
        else:
            if x == W - 1:
                y += 1
            else:
                x += 1

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

Submission status: Accepted

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

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

def gen():
  for h in range(H):
    for w in range(W):
      if h%2==0:
        yield (h,w)
      else:
        yield (h, W-1-w)

snake_gen = gen()
for i,a in enumerate(A):
  for _ in range(a):
    h, w = snake_gen.__next__()
    ans[h][w] = str(i+1)
    
for r in ans:
  print(' '.join(r))

Submission status: Accepted

Solution code:
import itertools
H,W=map(int,input().split())
N=int(input())
a=itertools.chain(*(itertools.repeat(i+1, cnt) for i,cnt in enumerate(map(int,input().split()))))

for h in range(H):
	it = map(str, itertools.islice(a, W))
	if h % 2 == 1:
		it = reversed(list(it))
	print(" ".join(it))

Submission status: Accepted

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

c = [[0 for i in range(w)] for j in range(h)]

p = [0,0]
for i in range(n):
    for j in range(a[i]):
        c[p[0]][p[1]]=str(i+1)
        if p[0]%2==0:
            if p[1]==w-1:
                p[0]+=1
            else:
                p[1]+=1
        else:
            if p[1]==0:
                p[0]+=1
            else:
                p[1]-=1

for i in range(h):
    print(' '.join(c[i]))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
*a,=map(int,input().split())
grid=[]
for i in range(n):
    for j in range(a[i]):
        grid.append(i+1)
for i in range(h):
    if i%2==0:
        print(*grid[i*w:i*w+w])
    else:
        print(*grid[i*w:i*w+w][::-1])

Submission status: Accepted

Solution code:
from collections import deque
import sys
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()

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

Submission status: Accepted

Solution code:
# 適当な道に沿って並べていくだけ
# 自然なindexで作ったあと偶数行を反転すればよい

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

import numpy as np
c = np.zeros(H*W,dtype=np.int32)

first = 0
for i,a in enumerate(A,1):
  c[first:first+a] = i
  first += a
  
c2d = c.reshape((H,W))

c2d[1::2,:] = c2d[1::2,::-1]

for i in range(H):
  print(' '.join(c2d[i].astype(str)))

Submission status: Accepted

Solution code:
import sys, os

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    h, w = f()
    n = f()[0]
    a = f()

    g = [ [0]*w for i in range(h)]

    cur = 0
    for i in range(h):
        if i%2==0:
            for j in range(w):
                if a[cur]==0:
                    cur+=1
                g[i][j] = cur+1
                a[cur] -= 1
        else:
            for j in reversed(range(w)):
                if a[cur]==0:
                    cur+=1
                g[i][j] = cur+1
                a[cur] -= 1

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

            if (j==w-1):
                print()
            else:
                print(' ', end='')


solve()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/arc080/tasks/arc080_b

import itertools
from collections import Counter
from collections import defaultdict
import bisect

def main():
    H, W = map(int, input().split())
    N = int(input())
    A = list(map(int, input().split()))
    ans = [[0] * W for _ in range(H)]

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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
N = int(input())
a = list(map(int,input().split()))
import copy
h,w = 0,0
flg = True
ansl = []
l = []
for i in range(N):
    for j in range(a[i]):
        if W > w:
            l.append(i+1)
            w += 1
        else:
            if flg == True:
                flg = False
                ansl.append(copy.deepcopy(l))
            else:
                flg =True
                ansl.append(copy.deepcopy(l[::-1]))
            w = 1
            l = []
            l.append(i+1)

if flg == True:
    ansl.append(copy.deepcopy(l))
else:
    ansl.append(copy.deepcopy(l[::-1]))

for l in ansl:
    print(' '.join(map(str,l)))

Submission status: Accepted

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math


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

color_count = {}
for i in range(N):
    color_count[i+1] = a[i]

color_count = dict(sorted(color_count.items(),key=lambda x:-x[1]))


mas = [[0 for i in range(W)] for j in range(H)]
colors = list(color_count.keys())

color = colors[0]
color_i = 0
color_cnt = color_count[color]
cnt = 0

for h_i in range(H):
    if h_i%2==0:
        for w_i in range(W):
            mas[h_i][w_i] = color
            cnt += 1
            if h_i == H - 1 and w_i == W-1:
                break
            if cnt == color_cnt:
                color_i += 1
                color = colors[color_i]
                cnt = 0
                color_cnt = color_count[color]
    else:
        for w_i in reversed(range(W)):
            mas[h_i][w_i] = color
            cnt += 1
            if h_i == H - 1 and w_i == 0:
                break
            if cnt == color_cnt:
                color_i += 1
                color = colors[color_i]
                cnt = 0
                color_cnt = color_count[color]

# print(mas)
for h_i in range(H):
    for w_i in range(W):
        print(mas[h_i][w_i],end=" ")
    print()

Submission status: Accepted

Solution code:
from functools import reduce
import math

def main():
    # 文字列の2進数を数値にする
    # '101' → '5'
    # 文字列の頭に'0b'をつけてint()にわたす
    # binary = int('0b'+'101',0)

    # 2進数で立っているbitを数える
    # 101(0x5) → 2
    # cnt_bit = bin(5).count('1')
    
    # N! を求める
    # f = math.factorial(N)

    # N の逆元
    # N_inv = pow(N,MOD-2,MOD)

    # nCr
    # Nの階乗 * rの階乗の逆元 * n-rの階乗の逆元
    
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)
    
    # 初期値用:十分大きい数(100億)
    INF = float("inf")

    # 大きな素数
    MOD = 10**9+7
    
    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'
    
    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())  
    # 変数:a=2 b=4 c=5 d =7
    
    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]    

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]    
    H, W = (int(_) for _ in input().split())
    N = int(input().rstrip())
    a = list(int(_) for _ in input().split())
    a_dict = dict()
    for i in range(N):
        a_dict[i+1] = a[i]

    a_dict_sorted = dict()
    for k, v in sorted(a_dict.items(), key=lambda x: -x[1]):
        a_dict_sorted[k] = v

    Grid = []
    for i in range(H):
        Grid.append(list ( -1 for j in range(W)))
        
    a_index = 0
    a_cnt = a[a_index]
    for h in range(H):
        for w in range(W):
            Grid[h][w] = a_index+1
            if a_cnt - 1 <=0:
                a_index +=1
                if(a_index == N):
                    break
                a_cnt = a[a_index]
            else:
                a_cnt -=1
                
    for h in range(H):
        if h % 2 ==1:
            Grid[h] = Grid[h][::-1]
    for h in range(H):
        print(' '.join(str(_) for _ in Grid[h]))
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))
color = 1
c = [[''for _ in range(w)]for _ in range(h)]
for i in range(h):
  for j in range(w):
    if a[color-1] == 0:
      color += 1
    c[i][j] = str(color)
    a[color-1] -= 1
for i in range(0,h,2):
  c[i] = c[i][::-1]
for i in range(h):
  print(' '.join(c[i]))

Submission status: Accepted

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

def print_ans(ans):
  for i in ans:
    for j in i:
      print(str(j) + ' ',end='')
    print()
  
ans = [[0 for i in range(W)] for j in range(H)]
ans[0][0] = 1
a[0] -= 1
color = 1
if a[0] == 0:
  color += 1
r,c = 0,0
direction = 0
for i in range(H*W-1):
  if direction ==0:
    if r >= H-1 or ans[r+1][c] != 0:
      direction = 1
      c += 1
    else:
      r+= 1
  elif direction == 1:
    if c >= W-1 or ans[r][c+1] != 0:
      direction = 2
      r -= 1
    else:
      c += 1
  elif direction == 2:
    if r == 0 or ans[r-1][c] != 0:
      direction = 3
      c -= 1
    else:
      r -= 1
  elif direction == 3:
    if c == 0 or ans[r][c-1] != 0:
      direction = 0
      r += 1
    else:
      c -= 1
  ans[r][c] = color
  a[color-1] -= 1
  if a[color-1] == 0:
    color += 1
print_ans(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

H,W=map(int, sys.stdin.readline().split())
N=input()
A=map(int, sys.stdin.readline().split())


L=[]

cnt=0
flag="r"
q=deque([]) 
for i,a in enumerate(A):
	for u in range(a):
		cnt+=1
		#print "u,i,a :::: ",u,i+1,a,cnt,flag
		if flag=="r":
			q.append(i+1)
		elif flag=="l":
			q.appendleft(i+1)

		if cnt==W:
			cnt=0
			L.append(q)
			q=deque([]) 
			if flag=="r": flag="l"
			elif flag=="l": flag="r"

for u in L:
	for x in u:
		print x,
	print

Submission status: Accepted

Solution code:
import numpy as np
h,w = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))
mat = np.zeros((h,w),dtype=int)
st = 0
for i in range(len(a)):
    for idx in range(st,st+a[i]):
        mat[idx//w][idx%w]=i+1
    st+=a[i]
for i in range(1,h,2):
    mat[i]=mat[i][::-1]
for i in range(h):
    for j in range(w):
        print(mat[i][j],end=" ")
    print("")

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
N = int(input())
a = list(map(int,input().split()))
l = []
for color,m in enumerate(a,1):
    l += [color]*m
for i in range(H):
    k = l[:W]
    l = l[W:]
    if i%2 != 0:
        k.reverse()
    print(*k)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))
ans = []
c = 1
for i in a:
    for j in range(i):
        ans.append(c)
    c += 1
for i in range(H):
    for j in range(W):
        if i % 2 == 0:
            print(ans[i * W + j], end = "")
        else:
            print(ans[i * W + W - 1 - j], end = "")
        if j < W - 1:
            print(" ", end = "")
        else:
            print()

Submission status: Accepted

Solution code:
height, wide = map(int, input().split())
n = int(input())
anslist = []

a = list(map(int, input().split()))
for i, j in enumerate(a):
    for l in range(j):
        anslist.append(i+1)
for k in range(height):
    t = anslist[k*wide:(k+1)*wide]
    if k % 2 == 1:
        t.reverse()
    print(' '.join(map(str, t)))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
p=1
k=0
s=0
for i in range(h):
    c=""
    for j in range(w):
        if i%2==1:
            c=str(p)+" "+c
        else:
            c+=str(p)+" "
        k+=1
        if a[p-1]==k:
            p+=1
            k=0
    else:
        print(c[:-1])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
p=1
k=0
s=0
for i in range(h):
    c=""
    for j in range(w*(i%2)-i%2,w*(1-i%2)-i%2,(1 if i%2==0 else -1)):
        if i%2==1:
            c=str(p)+" "+c
        else:
            c+=str(p)+" "
        k+=1
        if a[p-1]==k:
            p+=1
            k=0
    else:
        print(c[:-1])

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
lis = []
ans = []
nu = 0
nn = int(input())
li = list(map(int,input().split()))
for i in range(nn):
    for j in range(li[i]):
        if nu % 2 == 0:
            lis.append(str(i+1))
        else:
            lis.insert(0,str(i+1))
        if len(lis) == w:
            ans.append(str(" ".join(lis)))
            lis = []
            nu += 1
for i in range(h):print(ans[i])

Submission status: Accepted

Solution code:
H, W = list(map(int, input().split()))
N = int(input())
A = []
a = list(map(int, input().split()))
for i in range(N):
    A += [i + 1] * a[i]

L = [[0 for i in range(W)] for j in range(H)]
for i in range(H * W):
    if int((i // W)) % 2 == 0:
        L[int((i // W))][i % W] = A[i]
    else:
        L[int((i // W))][-1 - i % W] = A[i]

for i in range(H):
    L[i] = list(map(str, L[i]))


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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
n = int(input())
alist = list(map(int, input().split()))
cmap = [[-1 for _ in range(w)] for _ in range(h)]
i = 0
for ai, a in enumerate(alist):
  ai += 1
  for _a in range(a):
    if ((i + _a) // w) % 2 == 0:
      cmap[(i + _a) // w][(i + _a) % w] = ai
    else:
      cmap[(i + _a) // w][-((i + _a) % w + 1)] = ai
  i += a

for cm in cmap:
  print(*cm, sep=' ')

Submission status: Accepted

Solution code:

def start_process(high, width, number, color_data):
    ans_data = []
    for i in range(number):
        ans_data += [str(i + 1) for j in range(color_data[i])]
    for i in range(high):
        ans_kari = ans_data[i * width : (i + 1) * width]
        if i % 2 == 1:
            ans_kari = ans_kari[::-1]
        print(' '.join(ans_kari))

def main():
    high, width = map(int, input().split())
    number = int(input())
    color_data = list(map(int, input().split()))
    start_process(high, width, number, color_data)

if __name__ == '__main__':
    main()