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
## 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)])
    for i in range(h):
        tmp = []
        for j in range(w):
            tmp.append(aa.popleft())
        if i%2==1:
            tmp = tmp[::-1]
        print(*tmp)

if __name__ == '__main__':
    main()

Submission status: Accepted

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):
        if not aa: break
        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()
        if not aa: break
        for j in reversed(range(i,w-i)): # to left
            c[h-1-i][j] = aa.popleft()
        if not aa: break
        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: Accepted

Solution code:
import math
import fractions
#import sys
#input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

def rln(s):
    return range(len(s))

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

#################################################
#################################################
#################################################
#################################################



h,w = list(map(int, input().split()))
n=int(input())
a = list(map(int, input().split()))
num = []
for i in rln(a):
    for j in range(a[i]):
        num.append(i+1)
#print(num)
ans = [[-1 for i in range(w)]for j in range(h)]
for i in range(h*w):
    x = i//h
    y = i%h if(x%2==0) else h-1-i%h
    ans[y][x] = num[i]

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

Submission status: Accepted

Solution code:
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)]

z = 0
for i in range(len(a)):
    for j in range(a[i]):
        p = z + j
        y = p // w
        x = p % w
        if(y%2 == 1):x = w - x - 1
        c[y][x] = i+1
    z += a[i]
for b in c:
    s = map(str,b)
    print(' '.join(s))

Submission status: Accepted

Solution code:
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

def z_iterate(x, y, w):
    if y % 2:
        if x == 0:
            y += 1
        else:
            x -= 1
    else:
        if x == w-1:
            y += 1
        else:
            x += 1
    return x, y

h, w = map(int, inputs[0].split())
*A, = map(int, inputs[2].split())
grid = Grid(np.zeros((h, w), dtype=np.int))

x = y = 0
for i, a in enumerate(A, 1):
    for _ in range(a):
        grid[y, x] = i
        x, y = z_iterate(x, y, w)
print(grid)

Submission status: Accepted

Solution code:
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

h, w = map(int, inputs[0].split())
*A, = map(int, inputs[2].split())
grid = Grid(np.zeros((h, w), dtype=np.int))

x = y = 0
for i, a in enumerate(A, 1):
    for j in range(a):
        grid[y, x] = i
        if y % 2 == 0:
            if x == w-1:
                y += 1
            else:
                x += 1
        else:
            if x == 0:
                y += 1
            else:
                x -= 1
print(grid)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
n = int(input())
li = list(map(int,input().split()))
all_ans = []
for i,l in enumerate(li):
    bangou = i+1
    all_ans += [bangou]*l
#print(all_ans)
#[1, 1, 2, 3]
last = -1
for k in range(h):
    target = all_ans[last+1:last+1+w]
    if k%2 == 1:
        target.reverse()
    print(*target)
    last = last + w

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

h, w = na()
n = ni()
a = na()

ans = [[0] * w for _ in range(h)]
cur = 0
for i in range(h):
    if i % 2 == 0:
        for j in range(w):
            ans[i][j] = cur + 1
            a[cur] -= 1
            if a[cur] == 0:
                cur += 1
    else:
        for j in range(w - 1, -1, -1):
            ans[i][j] = cur + 1
            a[cur] -= 1
            if a[cur] == 0:
                cur += 1

for i in range(h):
    print(*ans[i], sep=" ")

Submission status: Accepted

Solution code:
from collections import Counter
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)]
b= []
for i,num in enumerate(a):
  b += num*[i+1]
#print(b)

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

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))
cur = [0,0]
grid = [[0]*w for _ in range(h)]
for i in range(n):
    color = str(i+1)
    remain = a[i]
    while remain > 0:
        y = cur[0]
        x = cur[1]
        grid[y][x] = color
        remain -= 1
        if y % 2 == 0:
            if x == w-1:
                cur[0] += 1
            else:
                cur[1] += 1
        else:
            if x == 0:
                cur[0] += 1
            else:
                cur[1] -= 1
for i in range(h):
    print(" ".join(grid[i]))

Submission status: Accepted

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

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

Submission status: Accepted

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

b = [0 for _ in range(N)]
b[0] = a[0]
for i in range(N-1):
    b[i+1] = b[i] + a[i]

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

pt = 0
for i in range(N):
    for j in range(a[i]):
        s,t = pt // W,pt % W
        C[s][t] = i+1
        pt += 1

for i in range(H):
    if i % 2 == 1:
        for j in range(W//2):
            C[i][j],C[i][W-j-1] = C[i][W-j-1],C[i][j]

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()))
G=[[0]*W for i in range(H)]
tate,yoko,now=0,0,0
rev=False
cnt=0
while(cnt<H*W):
    G[tate][yoko]=now+1
    a[now]-=1
    if(a[now]==0):
        now+=1
    if(not rev):
        if(tate<H-1):
            tate+=1
        else:
            yoko+=1
            rev=not rev
    else:
        if(tate>0):
            tate-=1
        else:
            yoko+=1
            rev=not rev
    cnt+=1
    
    
for i in range(H):
    print(*G[i])

Submission status: Accepted

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

lst = [[0]*W for i in range(H)]
cnt = 0
color = 1
i = 0

while True:
    for j in range(W):
        lst[i][j] = color
        cnt += 1
        if cnt == a[color-1]:
            color += 1
            cnt = 0
    if color == N+1:
        break
    i += 1
    for j in range(W-1,-1,-1):
        lst[i][j] = color
        cnt += 1
        if cnt == a[color-1]:
            color += 1
            cnt = 0
    if color == N+1:
        break
    i += 1
for row in lst:
    print(*row)

Submission status: Accepted

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 w == 1:
            direction = 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: Accepted

Solution code:
from collections import deque
h , w = map(int,input().split())
n = int(input())
a = list(map(int,input().split()))
p = 1
d = deque()
for i in range(n):
    for j in range(a[i]):
        if len(d) == w:
            print(*d)
            d = deque()
            p *= -1
        if p == 1:
            d.append(i+1)
        elif p == -1:
            d.appendleft(i+1)
if len(d) != 0:
    print(*d)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    h, w = map(int, input().split())
    n = int(input())
    a = [int(x) for x in input().split()]
    answer = [[0 for _ in range(w)] for _ in range(h)]
    dir = [[0, w, 1], [-1, -w - 1, -1]]
    count = 0
    color = 1
    for i in range(h):
        for j in range(dir[i % 2][0], dir[i % 2][1], dir[i % 2][2]):
            answer[i][j] = color
            count += 1
            if count == a[color - 1]:
                count = 0
                color += 1
    for ans in answer:
        print(" ".join(map(str, ans)))


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 i in range(h)]

num = a.pop(0)
color = 1
#print(num)
for i in range(h):
    for j in range(w):
        if num == 0:
            num = a.pop(0)
            color += 1

        c[i][j] = color
        num -= 1
for i in range(h):
    temp = c[i]
    if i % 2 == 1:
        temp = temp[::-1]
    print(*temp)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

h,w=mii()
n=ii()
arr=limii()

mat=[[0]*w for _ in range(h)]
temp=0
for i in range(h):

    if i%2==0:
        for j in range(w):
            mat[i][j]=temp+1
            arr[temp]-=1
            if arr[temp]==0:
                temp+=1
    if i%2==1:    
        for j in reversed(list(range(w))):
            mat[i][j]=temp+1
            arr[temp]-=1
            if arr[temp]==0:
                temp+=1

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

Submission status: Accepted

Solution code:

H, W = map(int, input().split())
N = int(input())
a = input().split()
a_i = [int(s) for s in a]
result = [[0] * W for i in range(H)]
count = 0
#奇数行目は逆からいれていけば解決!
for i in range(H):
    if(i % 2 == 0):
        #偶数行目は普通にいれていく
        for j in range(W):
            if(a_i[count] > 1):
                result[i][j] = count + 1
                a_i[count] -= 1
            elif(a_i[count] == 1):
                result[i][j] = count + 1
                count += 1
                
    if(i % 2 != 0):
        #奇数行目は逆から入れていく
        for j in range(W-1, -1, -1):
            if(a_i[count] > 1):
                result[i][j] = count + 1
                a_i[count] -= 1
            elif(a_i[count] == 1):
                result[i][j] = count + 1
                count += 1

                
print("\n".join([" ".join(map(str, l)) for l in result]))

Submission status: Accepted

Solution code:
# from collections import deque
import numpy as np
h,w = map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
# d=deque([0,0])
ans=np.array([[-1]*(w+2)] + [[-1]+[0]*w+[-1] for i in range(h)] + [[-1]*(w+2)])
opt = [[0,1],[1,0],[0,-1],[-1,0]]
temp=[1,1]
# print(ans)
for i in range(n):
    num=a[i]
    while num:
        ans[temp[0]][temp[1]] = i+1
        for j in opt:
            if ans[temp[0]+j[0]][temp[1]+j[1]] == 0:
                temp[0]+=j[0]
                temp[1]+=j[1]
                break
        num-=1

for i in range(1,h+1):
    print(*ans[i][1:-1])

Submission status: Accepted

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

for i, a in enumerate(A, 1):
  q += [str(i)] * a
  
for h in range(H):
  row = []
  for _ in range(W):
    row.append(q.pop(0))
  if h % 2 != 0:
    row.reverse()
  print(' '.join(x for x in row))

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): ans += [i+1]*a[i]
for hi in range(h):
    if hi % 2 == 0:
        print(*ans[hi*w:hi*w+w])
    else:
        print(*ans[hi*w:hi*w+w][::-1])

Submission status: Accepted

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

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

back = 1
c = 1
count = 0
for i in range(H):
  for j in range(W)[::back]:
    C[i][j] = c
    count+=1
    if count == A[c-1]:
      c += 1
      count = 0

  back = -back

for c in C:
  print(" ".join(map(str, c)))

Submission status: Accepted

Solution code:
import sys

h, w = map(int, sys.stdin.readline().rstrip().split())
n = int(sys.stdin.readline().rstrip())
a = list(map(int, sys.stdin.readline().rstrip().split()))
ans = []
i = 1
for ai in a:
    for j in range(ai):
        ans.append(i)
    i += 1

for i in range(h):
    if i % 2:
        print(' '.join(map(str, reversed(ans[w * i: w * (i + 1)]))))
    else:
        print(' '.join(map(str, ans[w * i: w * (i + 1)])))

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def MI(): return map(int, input().split())


def S(): return input()


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


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


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
# sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


# show_flg = True
show_flg = False


def main():
    H, W = MI()
    N = I()
    a = LI()
    v = []

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

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

    for i in range(len(v)):
        x = i % W
        y = i // W
        if y % 2 == 0:
            graph[y][x] = v[i]
        else:
            graph[y][W-x-1] = v[i]

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
b=[]
for i in range(n):
    for j in range(a[i]):
      b.append(i+1)
b=deque(b)
ans=[]
for hi in range(h):
  c=[0]*w
  for wi in range(w):
    if hi%2==0:
      j=wi
    else:
      j=w-wi-1
    c[j]=b.popleft()
  ans.append(c)
for ci in ans:
  print(' '.join(map(str,ci)))

Submission status: Accepted

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

h, w = map(int, input().split())
n = int(input())
nums = [int(i) for i in input().split()]

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

i = j = 0
t = 0
flag = True # Trueのとき、右方向
while i < h:
    num = nums[t]
    while num:
        matrix[i][j] = t + 1
        num -= 1
        if flag:
            if j + 1 == w:
                i += 1
                flag = False
            else:
                j += 1
        else:
            if j == 0:
                i += 1
                flag = True
            else:
                j -= 1
    t += 1

for r in matrix:
    print(*r)

Submission status: Accepted

Solution code:
H,W=map(int, input().split())
N=int(input())
A=list(map(int, input().split()))
#色N種類　1~N :i
#色iはai個
L=[]
for i,a in enumerate(A):
    L+=([str(i+1)]*a)
#print(L)
import numpy as np
ans=[[0]*W for _ in range(H)]
for h in range(H):
    for w in range(W):
        if h%2==0:
            ans[h][w]=L.pop(0)
        else:
            ans[h][-(w+1)]=L.pop(0)
#print(ans)
for h in range(H):
    print(" ".join(ans[h]))

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
 
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()
i = 0
C = [[0] * W for i in range(H)]
k = 0
cnt = 0
for h in range(H):
    if h % 2 == 0:
        for w in range(W):
            C[h][w] = k + 1
            A[k] -= 1
            if A[k] == 0:
                k += 1
    else:
        for w in range(W-1, -1, -1):
            C[h][w] = k + 1
            A[k] -= 1
            if A[k] == 0:
                k += 1

for c in C:
    print(*c, end="\n")

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
N=int(input())
L=list(map(int,input().split()))
ans=[]
for i in range(N):
	for j in range(L[i]):
		ans.append((i+1))
for i in range(H):
	if i%2==0:
		print(*ans[i*W:(i+1)*W])
	elif i%2==1:
		tmp=ans[i*W:(i+1)*W]
		print(*tmp[::-1])

Submission status: Accepted

Solution code:
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    H,W = LMIIS()
    N = II()
    A = LMIIS()
    ai = 0
    for i in range(H):
        
        line = deque()

        # from left to right
        if i % 2 == 0:
            j = 0
            while j < W:
                while j < W and A[ai] > 0:
                    # line += str(ai+1)
                    line.append(ai+1)
                    A[ai] -= 1
                    j += 1
                if A[ai] == 0 and ai < N-1:
                    ai += 1

            print(*line)
        # from right to left
        else:

            j = W-1
            while 0 <= j:
                while 0 <= j and A[ai] > 0:
                    # line += str(ai+1)
                    line.appendleft(ai+1)
                    A[ai] -= 1
                    j -= 1
                if A[ai] == 0 and ai < N-1:
                    ai += 1
            # print(line[::-1])
            print(*line)




    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    H,W = LMIIS()
    N = II()
    A = LMIIS()
    ai = 0
    for i in range(H):
        
        line = []

        # from left to right
        if i % 2 == 0:
            j = 0
            while j < W:
                while j < W and A[ai] > 0:
                    # line += str(ai+1)
                    line.append(ai+1)
                    A[ai] -= 1
                    j += 1
                if A[ai] == 0 and ai < N-1:
                    ai += 1

            print(*line)
        # from right to left
        else:
            j = W-1
            while 0 <= j:
                while 0 <= j and A[ai] > 0:
                    # line += str(ai+1)
                    line.append(ai+1)
                    A[ai] -= 1
                    j -= 1
                if A[ai] == 0 and ai < N-1:
                    ai += 1
            # print(line[::-1])
            print(*line[::-1])




    

if __name__ == '__main__':
    main()