Problem:
Chain Disappearance Puzzle We are playing a puzzle.
An upright board with H rows by 5 columns of cells, as shown in 
the figure below, is used in this puzzle.
A stone engraved with a digit, one of 1 through 9, is placed in each of 
the cells.
When three or more stones in horizontally adjacent cells are engraved 
with the same digit, the stones will disappear.
If there are stones in the cells above the cell with a disappeared 
stone, the stones in the above cells will drop down, filling the 
vacancy.   The puzzle proceeds taking the following steps.  When three or more stones in horizontally adjacent cells are 
engraved with the same digit, the stones will disappear. Disappearances 
of all such groups of stones take place simultaneously.  When stones are in the cells above the emptied cells, these stones drop down so that the emptied cells are filled.  After the completion of all stone drops, if one or more groups of 
stones satisfy the disappearance condition, repeat by returning to the 
step 1.  The score of this puzzle is the sum of the digits on the disappeared stones. Write a program that calculates the score of given configurations of stones.   Input The input consists of multiple datasets.
Each dataset is formed as follows. Board height H Stone placement of the row 1 Stone placement of the row 2 ... Stone placement of the row H  The first line specifies the height ( H ) of the puzzle board (1 ≤ H ≤ 10).
The remaining H lines give placement of stones on each of the rows from top to bottom.
The placements are given by five digits (1 through 9), separated by a space.
These digits are engraved on the five stones in the corresponding row, in the same order. The input ends with a line with a single zero. Output For each dataset, output the score in a line.
Output lines may not include any characters except the digits expressing the scores. Sample Input 1
6 9 9 9 9
5
5 9 5 5 9
5 5 6 9 9
4 6 3 6 9
3 3 2 9 9
2 2 1 1 1
10
3 5 6 5 6
2 2 2 8 3
6 2 5 9 2
7 7 7 6 1
4 6 6 4 9
8 9 1 1 8
5 6 1 8 1
6 8 2 1 2
9 6 3 3 5
5 3 8 8 8
5
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7
3
2 2 8 7 4
6 5 7 7 7
8 8 9 9 9
0 Output for the Sample Input 36
38
99
0
72

Solution (Python):
while True:
    h = int(input())
    if h == 0:
        break
    arr = [[-1 for i in range(h)], [-1 for i in range(h)], [-1 for i in range(h)], [-1 for i in range(h)], [-1 for i in range(h)]]
    midlen = h
    for i in range(h - 1, -1, -1):
        inp = list(map(int, input().split()))
        for j, e in enumerate(inp):
            arr[j][i] = e
    
    score = 0
    za = True
    while za:
        za = False
        for i, e in list(enumerate(arr[2]))[::-1]:
            for j in range(3):
                ge = 0
                for h in range(j, 5):
                    if len(arr[h]) > i:
                        if arr[h][i] == e:
                            ge += 1
                            continue
                    break
                if ge > 2:
                    za = True
                    for h in range(j, j + ge):
                        score += arr[h].pop(i)
    print(score)

Solution (Python):
while True:
    h = int(input())
    if h == 0:
        break
    else:
        stones_list = []
        for i in range(h):
            stones = list(map(int, input().split()))
            stones_list.append(stones)
        flag = 0
        point = 0
        while True:
            for i in range(h):
                cnt = 1
                num = stones_list[i][0]
                for j in range(1, 5):
                    if num == stones_list[i][j] and num != 0:
                        cnt += 1
                        if cnt >= 3 and j == 4:
                            point += num * cnt
                            flag = 1
                            for k in range(5-cnt, 5):
                                stones_list[i][k] = 0
                    else:
                        if cnt >= 3:
                            point += num * cnt
                            flag = 1
                            for k in range(j-cnt, j):
                                stones_list[i][k] = 0
                        num = stones_list[i][j]
                        cnt = 1
            for i in range(h-1, -1, -1):
                for j in range(5):
                    for k in range(i, h-1):
                        if stones_list[k+1][j] == 0:
                            stones_list[k+1][j] = stones_list[k][j]
                            stones_list[k][j] = 0
                        else:
                            break
            if flag == 0:
                print(point)
                break
            else:
                flag = 0

Solution (Python):
ans_list = []

while True:
    h = int(input())
    if not h:
        break

    stone = [list(map(int, input().split())) for i  in range(h)]
    ans = 0
    while True:
        key = 1
        for i in range(h):
            del_list = []
            for j in range(len(stone[0]) - 2):
                if stone[i][j:j + 3] == [stone[i][j], stone[i][j], stone[i][j]] and stone[i][j] != 0:
                    key = 0
                    del_list.append(j)
            for j in del_list:
                ans += sum(stone[i][j:j + 3])
                stone[i][j:j + 3] = [0, 0, 0]

        key2 = 1
        ij = 0
        while key2:
            import copy
            last_stone = copy.deepcopy(stone)
            key2 = 0
            for i in range(h - 1, -1, -1):
                for j in range(len(stone[i])):
                    if stone[i][j] == 0:
                        if i != 0:
                            key2 = 1
                            stone[i][j] = stone[i - 1][j]
                            stone[i - 1][j] = 0
            ij += 1
            if last_stone == stone:
                key2 = 0

        if key:
            break
    ans_list.append(ans)

for i in ans_list:
    print(i)

Solution (Python):
from functools import lru_cache


def DEBUG(*args): pass 


@lru_cache(maxsize=None)
def pat(s, n):
    return ' '.join([s] * n)


DEBUG(pat('1', 3))


def removeAll(xs, s):
    while s in xs:
        xs.remove(s)
        xs.append('
    return xs


def lmap(f, s): return list(map(f, s))


digits = lmap(str, range(1, 10))

def main(n):
    data = '\n'.join(map(lambda x: input(), range(n)))
    score = 0
    DEBUG(data)
    while True:
        removed = False
        sum1 = sum(map(lambda x: 0 if x == '
        for d in digits:
            if pat(d, 3) in data:
                data = data.replace(pat(d, 5), pat('0', 5))
                data = data.replace(pat(d, 4), pat('0', 4))
                data = data.replace(pat(d, 3), pat('0', 3))
                removed = True
        if removed == False:
            break
        DEBUG(data)
        score += (sum1 - sum(map(lambda x: 0 if x == '
        data = zip(*map(lambda x: x.split(), data.split('\n')))
        data = map(lambda x: list(x[::-1]), data)
        data = map(lambda x: removeAll(x, '0'), data)
        data = lmap(lambda s: ' '.join(s), zip(*data))
        data = '\n'.join(data[::-1])
        DEBUG(data)
    DEBUG(data)
    print(score)

while True:
    n = int(input())
    if n == 0: break
    main(n)

Solution (Python):
from functools import lru_cache

digits = list(map(lambda x: str(x),range(1,10)))

@lru_cache(maxsize=None) 
def check(s,n):  
    return ' '.join([s]*n)

def down(x):
    x = list(x[::-1])   
    while '0' in x:
        x.remove('0')
        x.append('
    return x

def main(n):
    data = '\n'.join(map(lambda x: input(), range(n)))  
    score = 0
    while True:
        removed = False
        for d in digits:
            if check(d, 3) in data:
                for i in range(5, 2, -1):
                    if check(d, i) in data:
                        score += int(d) * (data.count(check(d, i))*i)
                        data = data.replace(check(d, i), check('0', i))
                        removed = True
        if removed == False:
            break
        data = zip(*map(lambda x: x.split(), data.split('\n')))
        data = map(lambda x: down(x), data)
        data = list(map(lambda x: ' '.join(x),zip(*data)))
        data = '\n'.join(data[::-1])
    print(score) 


while True:
    n = int(input())
    if n == 0: break
    main(n)

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

def calc(p,x):
    return p*(100+x)//100


while True:
    H = int(input())
    if H == 0:
        break
    else:
        W = 5
        ban = [inpl() for i in range(H)]
        ans = 0
        while True:
            flag = False
            for y,[a1,a2,a3,a4,a5] in enumerate(ban):
                if a1 == a2 and a2 == a3 and a1 != -1:
                    flag = True
                    ban[y][0] = -1
                    ban[y][1] = -1
                    ban[y][2] = -1
                    ans += a1*3
                    if a3 == a4:
                        ban[y][3] = -1
                        ans += a4
                        if a4 == a5:
                            ban[y][4] = -1
                            ans += a5
                elif a2 == a3 and a3 == a4 and a2 != -1:
                    flag = True
                    ban[y][1] = -1
                    ban[y][2] = -1
                    ban[y][3] = -1
                    ans += a2*3
                    if a4 == a5:
                        ban[y][4] = -1
                        ans += a5
                elif a3 == a4 and a4 == a5 and a3 != -1:
                    flag = True
                    ban[y][2] = -1
                    ban[y][3] = -1
                    ban[y][4] = -1
                    ans += a3*3

            for _ in range(H):
                for y in reversed(range(1,H)):
                    for x in range(W):
                        if ban[y][x] == -1:
                            ban[y][x] = ban[y-1][x]
                            ban[y-1][x] = -1

            
            
            

            if not flag:
                break

        print(ans)

Solution (Python):
while True:
  w = 5
  h = input()

  if h == 0: break

  a = []
  for i in range(h):
    a.append(map(int, raw_input().split()))

  flag = True
  ans = 0
  while flag:
    flag = False

    for i in range(h - 1, -1, -1):
      cnts = [1 for _ in range(w)]
      for j in range(w - 1):
        if a[i][j] != -1 and a[i][j] == a[i][j + 1]:
          cnts[j + 1] += cnts[j]
      for j in range(w - 1, -1, -1):
        if a[i][j] != -1 and cnts[j] >= 3:
          ans += a[i][j] * cnts[j]
          for k in range(cnts[j]):
            a[i][j - k] = -1
            flag = True

    flag2 = True
    while flag2:
      flag2 = False
      for i in range(h - 1, 0, -1):
        for j in range(w):
          if a[i][j] == -1 and a[i - 1][j] != -1:
            (a[i][j], a[i - 1][j]) = (a[i - 1][j], a[i][j])
            flag2 = True
            """
    for i in range(h):
      for j in range(w):
        print a[i][j],
      print
    print
            """
  print ans

Solution (Python):
while 1:
    H = int(raw_input())
    if H == 0: break
    A = [map(int,raw_input().split())+[0] for _ in range(H)]
    ans = 0
    while 1:
        vanish = False
        for h in range(H):
            l = r = 0
            while r < 6:
                if A[h][r] != A[h][l]:
                    if r-l >= 3:
                        if A[h][l] == 0:break
                        ans += A[h][l]*(r-l)
                        A[h][l:r] = [0]*(r-l)
                        vanish = True
                    l = r
                r += 1
        if not vanish: break
        for h in range(H)[::-1]:
            for w in range(5):
                if A[h][w] == 0:
                    for hh in range(h)[::-1]:
                        if A[hh][w] != 0:
                            A[h][w] = A[hh][w]
                            A[hh][w] = 0
                            break
    print ans

Solution (Python):
while 1:
	H = int(raw_input())
	if H == 0:
		break
	Board = [[0 for j in range(H+1)] for i in range(6)]
	for j in range(H):
		inputs = map(int,raw_input().split(" "))
		for i in range(5):
			Board[i][H-j] = inputs[i]
	total_score = 0
	tmp_score = -1
	while tmp_score != 0:
		tmp_score = 0
		tmpBoard = [[0] for i in range(6)]
		for j in range(1,H+1):
			con_num = 1
			for i in range(1,6):
				if Board[i][j] == Board[i-1][j]:
					con_num += 1
				else :
					if con_num >= 3:
						tmp_score += con_num * Board[i-1][j]
					else :
						for h in range(con_num):
							tmpBoard[i-1-h].append(Board[i-1-h][j])
							tmpBoard[i-1-h][0] += 1
					con_num = 1
		total_score += tmp_score
		Board = [line + [0 for j in range(H-line[0])] for line in tmpBoard]
	print total_score

Solution (Python):
while 1:
	H = int(raw_input())
	if H == 0:
		break
	Board = [[0 for j in range(H+1)] for i in range(6)]
	for j in range(H):
		inputs = map(int,raw_input().split(" "))
		for i in range(5):
			Board[i][H-j] = inputs[i]
	total_score = 0
	tmp_score = -1
	while tmp_score != 0:
		tmp_score = 0
		tmpBoard = [[0 for j in range(H+1)] for i in range(6)]
		for j in range(1,H+1):
			con_num = 1
			for i in range(1,6):
				if Board[i][j] == Board[i-1][j]:
					con_num += 1
				else :
					if con_num >= 3:
						tmp_score += con_num * Board[i-1][j]
					else :
						for h in range(con_num):
							tmpBoard[i-1-h][0] += 1
							tmpBoard[i-1-h][tmpBoard[i-1-h][0]] = Board[i-1-h][j]
					con_num = 1
		total_score += tmp_score
		Board = tmpBoard
	print total_score

Solution (Python):
while True:
    N = int(input())
    if not N: break
    cells = [[int(x) for x in input().split()] for _ in range(N)]
    point = 0
    while True:
        flag = False
        for i, cell in enumerate(cells):
            j = 0
            while j < 5:
                s, color = j, cell[j]
                while j < 5 and cell[j] == color:
                    j += 1
                if color != 0 and j - s >= 3:
                    point += color * (j - s)
                    cell[s:j] = [0] * (j-s)
                    flag = True
        for i in range(5):
            for j in reversed(range(N)):
                s = j
                while s >= 0 and not cells[s][i]:
                    s -= 1
                if s >= 0:
                    cells[j][i], cells[s][i] = cells[s][i], cells[j][i]
        if not flag:
            break
    print(point)

Solution (Python):
from itertools import zip_longest

while True:
    n = int(input())
    if not n:
        break
    field = [list(map(int, input().split())) for _ in range(n)]
    field.reverse()
    score = 0
    while True:
        no_more_disappear = True

        for y, row in enumerate(field):
            for i, stone in enumerate(row[:3]):
                if stone is None:
                    continue
                cnt = 1
                for stone2 in row[i + 1:]:
                    if stone != stone2:
                        break
                    cnt += 1
                if cnt >= 3:
                    row[i:i + cnt] = [None] * cnt
                    score += stone * cnt
                    no_more_disappear = False

        if no_more_disappear:
            break

        fieldT = map(lambda row: filter(None, row), zip(*field))
        field = list(map(list, zip_longest(*fieldT)))

    print(score)

Solution (Python):
from itertools import zip_longest

while True:
    n = int(input())
    if not n:
        break
    field = [list(map(int, input().split())) for _ in range(n)]
    field.reverse()
    score = 0
    while True:
        no_more_disappear = True

        for row in field:
            for i, stone in enumerate(row[:3]):
                if stone is None:
                    continue
                cnt = 1
                for stone2 in row[i + 1:]:
                    if stone != stone2:
                        break
                    cnt += 1
                if cnt >= 3:
                    row[i:i + cnt] = [None] * cnt
                    score += stone * cnt
                    no_more_disappear = False

        if no_more_disappear:
            break

        fieldT = map(lambda row: filter(None, row), zip(*field))
        field = list(map(list, zip_longest(*fieldT)))

    print(score)

Solution (Python):
while 1:
    h = input()
    if h == 0:
        break
    M = [map(int, raw_input().split()) for i in xrange(h)]
    ans = 0
    update = 1
    while update:
        update = 0
        for i in xrange(h):
            cnt = 0; prev = None
            for j in xrange(5):
                if prev != M[i][j]:
                    if cnt >= 3:
                        if prev is not None:
                            for k in xrange(cnt):
                                M[i][j - k - 1] = None
                            ans += cnt * prev
                            update = 1
                    cnt = 1
                else:
                    cnt += 1
                prev = M[i][j]
            if cnt >= 3:
                if prev is not None:
                    for k in xrange(cnt):
                        M[i][5 - k - 1] = None
                    ans += cnt * prev
                    update = 1
        for j in xrange(5):
            cur = h-1
            for i in xrange(h-1, -1, -1):
                if M[i][j] is not None:
                    if i < cur:
                        M[cur][j] = M[i][j]
                        M[i][j] = None
                    cur -= 1
    print ans

Solution (Python):
while 1:
    h = input()
    if h == 0:
        break
    M = [map(int, raw_input().split()) for i in xrange(h)]
    ans = 0
    update = 1
    while update:
        update = 0
        for i in xrange(h):
            prev = 0; cnt = 0
            for j in xrange(5):
                if prev != M[i][j]:
                    if cnt >= 3:
                        M[i][j-cnt:j] = [0]*cnt
                        ans += prev * cnt
                        update |= prev
                    cnt = 1
                else:
                    cnt += 1
                prev = M[i][j]
            if cnt >= 3:
                M[i][5-cnt:5] = [0]*cnt
                ans += prev * cnt
                update |= prev
        for j in xrange(5):
            cur = h-1
            for i in xrange(h-1, -1, -1):
                if M[i][j]:
                    if cur != i:
                        M[cur][j] = M[i][j]
                        M[i][j] = 0
                    cur -= 1
    print ans

Solution (Python):
while True:
    score = 0
    h = int(input())
    if h == 0: break
    w = 5

    field = [list(map(int, input().split())) for x in range(h)]

    def delete(field):
        flg = True
        for row in field:
            target = None
            cnt = 0
            fs = []
            f = None
            t = None
            for i, cell in enumerate(row):
                if target != None and cell == target:
                    cnt += 1
                else:
                    if cnt >= 2:
                        f = fs[-1]
                        t = i - 1
                    fs.append(i)
                    target = cell
                    cnt = 0
            if cnt >= 2:
                f = fs[-1]
                t = i

            if f != None:
                global score
                score += (t - f + 1) * row[f]
                for i in range(f, t + 1):
                    row[i] = None
                flg = False
        if flg: return flg
        return field


    def drop(field):
        for y, row in enumerate(field[:-1]):
            for x, cell in enumerate(row):
                if field[y + 1][x] == None:
                    for n in range(y + 1, 0, -1):
                        field[n][x] = field[n - 1][x]
                    else:
                        field[0][x] = None
        return field

    while True:
        field = delete(field)
        if field == True:
            break
        field = drop(field)
        
        
    print(score)

Solution (Python):
def scan_row(row):
    if row[0] == row[1] == row[2]:
        if row[2] == row[3]:
            if row[3] == row[4]:
                return (row[0]*5, 0, 5)
            else:
                return (row[0]*4, 0 ,4)
        else:
            return (row[0]*3, 0 ,3)
    elif row[1] == row[2] == row[3]:
        if row[3] == row[4]:
            return (row[1]*4, 1, 4)
        else:
            return (row[1]*3, 1, 3)
    elif row[2] == row[3] == row[4]:
        return (row[2]*3 , 2, 3)
    return (-1,-1,-1)

while True:
    H = int(input())
    if H == 0: break
    src = [list(map(int,input().split())) for i in range(H)]
    mem = [[] for i in range(5)]
    for row in reversed(src):
        for x in range(5):
            mem[x].append(row[x])
    ans = 0
    while True:
        erase = []
        for h in range(max(map(len,mem))):
            row = tuple(map(lambda x:x[h] if h < len(x) else -1, mem))
            score,start,l = scan_row(row)
            if score <= 0: continue
            ans += score
            erase.append((h,start,l))
        if not erase: break
        for h,start,l in reversed(erase):
            for i in range(start,start+l):
                mem[i].pop(h)
    print(ans)

Solution (Python):
def calc(puzzle,H,score):
    flag=False
    for i in range(H-1,-1,-1):
        stones=[]
        for j in range(5):
            now=[j,puzzle[j][i]]
            if (len(stones)==0 or stones[-1][1]==now[1]) and now[1]!=0: stones.append(now)
            elif len(stones)<3: stones=[now]
            else: break
        if len(stones)>2:
            flag=True
            score+=stones[0][1]*len(stones)
            for stone in stones:
                puzzle[stone[0]].pop(i)
                puzzle[stone[0]].append(0)

    if flag==True:
        return calc(puzzle,H,score)
    else:
        return score

if __name__=="__main__":
    while True:
        score=0
        H=int(input())
        if H==0:
            break
        puzzle=[[] for _ in range(5)]
        for i in range(H):
            temp=list(map(int,input().split()))
            for j in range(5):
                puzzle[j].insert(0,temp[j])
        score=calc(puzzle,H,score)
        print(score)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    while True:
        h = I()
        if h == 0:
            break

        a = [LI() for _ in range(h)]
        f = True
        r = 0
        while f:
            f = False
            d = [[0]*5 for _ in range(h)]
            for i in range(h):
                for j in range(3):
                    if a[i][j] > 0 and a[i][j] == a[i][j+1] and a[i][j] == a[i][j+2]:
                        d[i][j] = 1
                        d[i][j+1] = 1
                        d[i][j+2] = 1
                        f = True
            for i in range(h):
                for j in range(5):
                    if d[i][j] == 1:
                        r += a[i][j]
                        a[i][j] = 0

            for i in range(h-2,-1,-1):
                for j in range(5):
                    if a[i][j] <= 0:
                        continue
                    k = i
                    while k < h-1 and a[k+1][j] == 0:
                        a[k+1][j] = a[k][j]
                        a[k][j] = 0
                        k += 1

        rr.append(r)

    return '\n'.join(map(str, rr))


print(main())

Solution (Python):

from collections import Counter
def inpl(): return list(map(int, input().split()))

N = int(input())
while N:
    B = [inpl() for _ in range(N)]
    ans = -1
    tmp = 1
    while tmp:
        ans += tmp
        tmp = 0
        erase = [set() for _ in range(5)]
        for i in range(N):
            for j in range(1, 4):
                if B[i][j-1] == B[i][j] == B[i][j+1]:
                    for k in range(j-1, j+2):
                        erase[k].add(i)
        B2 = list(map(list, zip(*B)))
        for j in range(5):
            for i in sorted(erase[j], reverse=True):
                tmp += B[i][j]
                del B2[j][i]
            B2[j] = [0]*len(erase[j]) + B2[j]
        B = list(map(list, zip(*B2)))
    print(ans)
    N = int(input())

Solution (Python):
a = int(input())
global s
s = 0

def de(ppp,h):
	re = False
	co  = 0
	global s
	for lo in ppp:
		for j ,cell in enumerate(lo):
			k = j
			p = j
			if k <= 2:
				while cell == lo[k+1] and cell != None:
					co += 1
					if k == 3:
						j = k+1
						break
					k += 1
					j = k
				if co >= 2:
					re = True
					s += (co+1)*cell
					for l in range(5):
						if l >= p and l <= j:
							lo[l] = None
				co = 0

	return re



def mo(ppp,h):
	for i ,roe in enumerate(ppp):
		for j , cell in enumerate(roe):
			kkk = i
			while i != 0 and ppp[kkk-1][j] == None:
				ppp[kkk-1][j] = ppp[kkk][j]
				ppp[kkk][j] = None
				if kkk == 1:
					break
				kkk -= 1


while a != 0:
	ppp = [list(map(int,input().split())) for i in range(a)]
	ppp.reverse()
	while(de(ppp,a) == True):
		mo(ppp,a)
	print(s)

	s = 0

	a = int(input())

Solution (Python):
while True:
    H = int(input())
    if H == 0:  break

    score = 0
    game = [[None] * 5 for _ in range(H)]
    for i in reversed(range(H)):
        game[i] = [int(x) for x in input().split()]

    try_again = True
    while(try_again):
        
        try_again = False
        for i in range(H):
            for j in range(3):
                if game[i][j] == None:  continue
                if game[i][j] == game[i][j + 1] == game[i][j + 2]:
                    try_again = True
                    num = game[i][j]
                    game[i][j] = game[i][j + 1] = game[i][j + 2] = None
                    score += 3 * num
                    for k in range(j + 3, 5):
                        if game[i][k] != num: break
                        game[i][k] = None
                        score += num
                    break

        
        for i in range(1, H):
            for j in range(5):
                k = i
                while k > 0 and game[k - 1][j] == None:
                    k -= 1
                game[k][j], game[i][j] = game[i][j], game[k][j]

    print(score)

Solution (Python):
from collections import deque    

def cnt(aa):
    for i in range(3):
        if aa[i]!=0 and aa[i]==aa[i+1] and aa[i+1]==aa[i+2]:
            n=aa[i]
            j=i
            k=3
            if i+3<5 and aa[i+2]==aa[i+3]:
                k=4
                if i+4<5 and aa[i+3]==aa[i+4]:
                    k=5
            return n,j,k                             
    return 0,0,0                        
                             
while True:
    h=int(input())
    if h==0:
        break
    a=[[0]*5 for i in range(h)]
    for i in range(h):
        a[i]=list(map(int,input().split()))

    a.reverse()

    p=0
    while True:
        dq = deque()
        for i in range(h):
            n,j,k=cnt(a[i])
            p+=n*k
            if n!=0:
                dq.append((i,j,k))

        if len(dq)==0 :
            break
        while dq:
            hi,j,k=dq.popleft()

            for jj in range(j,j+k):
                a[hi][jj]=0

        for jj in range(5):
            for ii in range(h):
                if a[ii][jj]==0:
                    for iii in range(ii+1,h):
                        if a[iii][jj]!=0:
                            a[ii][jj]=a[iii][jj]
                            a[iii][jj]=0
                            break

    print(p)

Solution (Python):
W = 5

def calc_score(ban, score):
    add_score = 0
    after_ban = []
    H = len(ban)
    for h in range(H):
        row = []
        cnt = 1
        cur = ban[h][0]
        for w in range(1, W):
            if cur == ban[h][w]:
                cnt += 1
            else:
                row.append([cur, cnt])
                cur = ban[h][w]
                cnt = 1
        row.append([cur, cnt])

        after_row = []
        for cur, cnt in row:
            if cnt >= 3:
                add_score += cur * cnt
                after_row.extend([0]*cnt)
            else:
                after_row.extend([cur]*cnt)
        after_ban.append(after_row)

    
    for _ in range(10):
        for h in range(0, H-1):
            for w in range(W):
                if after_ban[h+1][w] == 0:
                    after_ban[h+1][w] = after_ban[h][w]
                    after_ban[h][w] = 0

    score += add_score
    if add_score == 0:
        return score
    else:
        return calc_score(after_ban, score)

ans = []

while True:
    H = int(input())
    if H == 0:
        break
    ban = [list(map(int, input().split())) for _ in range(H)]
    ans.append(calc_score(ban, 0))

print(*ans, sep='\n')

Solution (Python):

def delete(M):
    point = 0
    for row in M:
        for l in range(len(row)-1):
            for r in range(l + 1, len(row)):
                if row[l] != row[r]:
                    break
            if r - l >= 3:
                point += (r - l) * row[l]
                for i in range(l, r):
                    row[i] = 0
                break

    return point


def drop(M):
    for c in range(5):
        nums = []
        for i in range(len(M)-1, -1, -1):
            if M[i][c] != 0:
                nums.append(M[i][c])
            M[i][c] = 0

        for i in range(len(nums)):
            M[len(M)-1-i][c] = nums[i]


def solve(h, M):
    result = 0
    while True:
        point = delete(M)
        if point == 0:
            break
        result += point
        
        
        
        
        drop(M)
        
        
        
    print(result)


if __name__ == "__main__":
    while True:
        h = int(input())
        if h == 0:
            break
        M = [list(map(int, input().split())) + [0] for _ in range(h)]
        solve(h, M)

Solution (Python):
def main(h):
    lst=[list(map(int,input().split())) for _ in range(h)]

    check=1
    sm=0
    while check:
        check=0
        for i in range(h):
            for j in range(3):
                if lst[i][j]==0 : continue
                if lst[i][j+1]!=lst[i][j] : continue
                if lst[i][j+2]!=lst[i][j] : continue
                sm+=3*lst[i][j]
                for k in range(j+3,5):
                    if lst[i][k]==lst[i][j]:
                        lst[i][k]=0
                        sm+=lst[i][j]
                    else : break

                lst[i][j:j+3]=[0,0,0]
                check=1
        for i in range(h-1,0,-1):
            for j in range(5):
                if lst[i][j]==0:
                    for k in range(i-1,-1,-1):
                        if lst[k][j]==0 : continue
                        lst[i][j]=lst[k][j]
                        lst[k][j]=0
                        break
    
    print(sm)
    

while 1:
    h=int(input())
    if h==0 : break
    main(h)