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

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def check(y,x):
        res = 0
        c = s[x][y]
        for x in range(x,5):
            if s[x][y] != c:
                break
            res += 1
        if res < 3:
            return 0
        else:
            return res

    def update(y,x,d):
        for i in range(x,x+d):
            s[i][y] = 0

    def fall(s):
        q = [[] for i in range(5)]
        for x in range(5):
            for y in range(h):
                if s[x][y]:
                    q[x].append(s[x][y])
            for y in range(h-len(q[x])):
                q[x].append(0)
        return q

    while 1:
        h = I()
        if h == 0:
            break
        s = LIR(h)
        s = [[s[-1-y][x] for y in range(h)] for x in range(5)]
        ans = 0
        f = 1
        while f:
            f = 0
            for y in range(h):
                for x in range(3):
                    if s[x][y]:
                        d = check(y,x)
                        ans += s[x][y]*d
                        if d:
                            update(y,x,d)
                            f = 1
            if f:
                s = fall(s)
        print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
import sys,queue,math
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = 10**18
MOD = 10**9 + 7
LI = lambda : [int(x) for x in input().split()]
_LI = lambda : [int(x)-1 for x in input().split()]

while True:
    N = int(input())
    if N == 0 : break

    puyo = [[int(x) for x in input().split()] + [0] for _ in range(N)]
    p = 0
    update = True
    while update:
        update = False
        for i in range(N):
            cl = puyo[i][0]
            cnt = cl > 0
            for j in range(1,6):
                if puyo[i][j] == cl and cl > 0:
                    cnt += 1
                else:
                    if cnt >= 3:
                        p += cl * cnt
                        for k in range(cnt):
                            puyo[i][j-k-1] = 0
                        update = True
                    cl = puyo[i][j]
                    cnt = cl > 0
        for i in range(N-1,0,-1):
            for j in range(5):
                if puyo[i][j] > 0: continue
                x = i
                while x > 0:
                    x -= 1
                    if puyo[x][j] > 0:
                        puyo[i][j] = puyo[x][j]
                        puyo[x][j] = 0
                        break
    print (p)

Solution (Python):
bi = 10

while True:

    H = int(input())
    if H == 0:
        break

    a = []

    for i in range(H):

        A = list(input().split())
        a.append(A)

    ans = 0
    rep = True
    while rep:

        b = [[False] * 5 for i in range(H)]
        
        rep = False

        for i in range(H):
            for j in range(5):

       

                if j - 2 >= 0 and a[i][j-2] == a[i][j-1] and a[i][j-1] == a[i][j]:
                    b[i][j] = True
                if j - 1 >= 0 and j + 1 < 5 and a[i][j-1] == a[i][j] and a[i][j+1] == a[i][j]:
                    b[i][j] = True
                if j + 2 < 5  and a[i][j+2] == a[i][j+1] and a[i][j+1] == a[i][j]:
                    b[i][j] = True

        for i in range(H):
            for j in range(5):
                if b[i][j]:
                    rep = True
                    
                    ans += int(a[i][j])
                    a[i][j] = bi
                    bi += 0.1
        rep2 = True
        while rep2:
            rep2 = False
            
            for i in range(H-1):
                i = H-2-i
                for j in range(5):

                    if int(a[i][j]) <= 9 and int(a[i+1][j]) > 9:
                        a[i+1][j] = a[i][j]
                        a[i][j] = bi
                        bi += 0.1
                        rep2 = True
    
    print (ans)

Solution (Python):
while True:
    n = int(input())
    if n == 0:
        break
    
    field = [input().split() for _ in range(n)]
    field = list(reversed(field))
    score = 0

    while True:

        f = True

        for row in field:
            clear_index = set()
            for i in range(3):
                if row[i] == -1:
                    continue
                if row[i] == row[i+1] and row[i+1] == row[i+2]:
                    f = False
                    clear_index.add(i)
                    clear_index.add(i+1)
                    clear_index.add(i+2)

            for i in clear_index:
                score += int(row[i])
                row[i] = -1
        
        if f:
            break

        for i,row in enumerate(field):
            for j in range(5):
                if row[j] != -1:
                    continue
                
                for k in range(i+1,n):
                    if field[k][j] != -1:
                        field[k][j],row[j] = row[j],field[k][j]
                        break
    print(score)

Solution (Python):
def fall(S,H):
    for h in range(H-1):
        for i in range(5):
            if S[h][i]=="0":
                S[h][i] = S[h+1][i]
                S[h+1][i] = "0"
    return S
while True:
    H = int(input())
    if H==0:
        break
    S = [list(input().split()) for i in range(H)]
    S = S[::-1]
    ans = 0
    k = 1
    while k!=0:
        k = 0
        for h in range(H):
            s = S[h]
            for l in range(3):
                for r in range(5,2+l,-1):
                    if s[l]=="0":
                        continue
                    if s[l:r].count(s[l])==(r-l):
                        k = 1
                        ans += int(s[l])*(r-l)
                        S[h][l:r] = ["0"]*(r-l)
        for i in range(H):
            S = fall(S,H)
    print(ans)

Solution (Python):
from inspect import currentframe


def debug_print(s):
    
    return


def debug_key(*args):
    names = {id(v): k for k, v in currentframe().f_back.f_locals.items()}
    debug_print(', '.join(names.get(id(arg), '???')+' = '+repr(arg) for arg in args))


def solve(H, stone):
    debug_print("\n-----solve-----")
    debug_key(stone)

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

    return


if __name__ == '__main__':

    while True:
        H_input = int(input())
        if H_input == 0:
            break
        stone_input = [list(map(int, input().split())) for _ in range(H_input)]
        solve(H_input, stone_input)

Solution (Python):
def main(n):
    f = [list(map(int, input().split())) for i in range(n)]
    d = True
    ans = 0
    while d:
        d = False
        for i in range(n):
            l = []
            for k in range(3):
                if f[i][k] == 0:
                    continue
                if f[i][k] == f[i][k + 1] == f[i][k + 2]:
                    l.append(k)
                    l.append(k + 1)
                    l.append(k + 2)
            if l == []:
                continue
            l = list(set(l))
            b = f[i][l[0]]
            d = True
            for k in l:
                ans += b
                f[i][k] = 0
        if d:
            for i in range(n-1,-1,-1):
                for k in range(5):
                    x = i
                    while f[x][k]:
                        if x < n - 1:
                            if f[x + 1][k] == 0:
                                f[x+1][k] = f[x][k]
                                f[x][k] = 0
                                x += 1
                                continue
                        break
    print(ans)

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

Solution (Python):

while True:
    h = int(input())
    if h == 0:
        break
    stones = [list() for i in range(h)]
    for i in range(h):
        stones[i] = list(map(int, input().split()))
    ans = 0
    while True:
        
        tmp = 0
        for y in range(h):
            for j in range(3):
                num = stones[y][j]
                count = 0
                for k in range(j, 5):
                    if num == stones[y][k]:
                        count += 1
                    else:
                        break
                if count >= 3:
                    for k in range(j, j+count):
                        stones[y][k] = 0
                    tmp += count * num
                    break
        if tmp == 0:
            break
        ans += tmp
        
        for x in range(5):
            settle = h-1
            for y in range(h-1, -1, -1):
                if stones[y][x] != 0:
                    tmp = stones[y][x]
                    stones[y][x] = 0
                    stones[settle][x] = tmp
                    settle -= 1
    print(ans)

Solution (Python):
from collections import deque

ans_list = []

def solve():
    H = int(input())
    if H == 0:
        return "end"
    grid = [list(map(int,input().split())) for _ in range(H)]
    
    def erase(i):
        res = 0
        a = grid[i]
        dq = deque()
        for j in range(5):
            if not dq:
                dq.append(a[j])
            elif dq[-1] == a[j] and a[j] != 0:
                dq.append(a[j])
            else:
                if len(dq) >= 3:
                    res += dq[-1] * len(dq)
                    
                    for nj in range(j-len(dq),j):
                        grid[i][nj] = 0
                dq.clear()
                dq.append(a[j])
        if len(dq) >= 3:
            res += dq[-1] * len(dq)
            
            for nj in range(j+1-len(dq),j+1):
                grid[i][nj] = 0
        return res
    
    def drop(j):
        b = [grid[i][j] for i in range(H)]
        dq = deque()
        for i in range(H)[::-1]:
            
            if b[i] != 0:
                dq.append(b[i])
        for ni in range(H)[::-1]:
            if dq:
                num = dq.popleft()
            else:
                num = 0
            grid[ni][j] = num

    score = 0

    while True:
        res = 0
        for i in range(H):
            res += erase(i)
        score += res
        if res == 0:
            break
        for j in range(5):
            drop(j)
    
    return score

while True:
    ans = solve()
    if ans == "end":
        break
    ans_list.append(ans)

for ans in ans_list:
    print(ans)

Solution (Python):
def dis():
    k=0
    for i in range(n):
        for j in range(3):
            if l[i][j]==0:
                continue
            re=1
            for z in range(1,100):
                if j+z>4:break
                if l[i][j]==l[i][j+z]:
                    re+=1
                else: break
            if re<3:continue
            k+=l[i][j]*re
            for x in range(re):
                l[i][j+x]=0
    return k
def dow():
    for i in range(n-1,0,-1):
        for j in range(4,-1,-1):
            if l[i][j]==0:
                for z in range(1,i+1):
                    if l[i-z][j]!=0:
                        l[i][j],l[i-z][j]=l[i-z][j],l[i][j]
                        break
while True:
    n=int(input())
    if n==0:exit()
    l=[list(map(int,input().split())) for _ in range(n)]
    ans=0
    k=dis()
    while k!=0:
        dow()
        ans+=k
        k=dis()
    print(ans)

Solution (Python):
while True:
  h = int(input())
  if h==0:
    break
  board = [list(map(int, input().split())) for i in range(h)]
  ans = 0

  while True:
    tans = 0
    for y in range(h):
      begin, end = 0, 0
      for x in range(1, 5):
        if board[y][x]==board[y][x-1]:
          end = x
        elif end-begin+1>=3:
          break
        else:
          begin = x
          continue
      if end-begin+1>=3:
        tans += board[y][begin]*(end-begin+1)
        for x in range(begin, end+1):
          board[y][x] = 0

    move = True
    while move:
      move = False
      for y in range(1, h):
        for x in range(5):
          if board[y][x]==0 and board[y-1][x]==0:
            continue
          elif board[y][x]==0:
            board[y][x], board[y-1][x] = board[y-1][x], board[y][x]
            move = True
    if tans>0:
      ans += tans
    else:
      break
  print(ans)

Solution (Python):
from itertools import groupby

def main():
    while True:
        h = int(input())
        w = 5
        if h == 0: break

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

        score = 0
        while True:
            scoreinc = 0
            for i in range(h):
                c = 0
                for key, value in groupby(field[i]):
                    newlist = list(value)
                    if len(newlist) >= 3:
                        scoreinc += newlist[0] * len(newlist)
                        newlist = [0 for i in range(len(newlist))]
                        
                    if c == 0:
                        field[i] = newlist
                    else:
                        field[i] += newlist
                    c += 1


            if scoreinc == 0: break
            score += scoreinc

            for i in range(w):
                ydata = []
                for j in range(h):
                    ydata.append(field[j][i])
                    
                ydata = sorted(ydata, key = return0)
                
                for j in range(h):
                    field[j][i] = ydata[j]

        
        print(score)

def return0(num):
    if num == 0: return 0
    else: return 1
main()

Solution (Python):
class Game:
    def __init__(self, mp, height):
        self.mp = mp
        self.height = height
        self.score = 0
        self.erase_flag = False

    def erase(self):
        for y in range(self.height):
            line = self.mp[y]
            new_line, add_score = self.fix(line)
            self.mp[y] = new_line
            self.score += add_score
            if add_score != 0:self.erase_flag = True

    def fix(self, line):
        add_score = 0
        new_line = line
        for length in range(5, 2, -1):
            for left in range(5 - length + 1):
                if all(map(lambda x:x==line[left], line[left:left+length])):
                    add_score = line[left] * length
                    new_line = line[:left] + [0] * length + line[left+length:]
                    return new_line, add_score
        return new_line, add_score

    def fall(self):
        for x in range(5):
            col = []
            for y in range(self.height):
                if self.mp[y][x] != 0:
                    col.append(self.mp[y][x])
            col = [0] * (self.height - len(col)) + col
            for y in range(self.height):
                self.mp[y][x] = col[y]

    def run(self):
        while True:
            self.erase_flag = False
            self.erase()
            if not self.erase_flag:break
            self.fall()

    def print_state(self):
        print(*self.mp, sep="\n")
        print(self.score)


while True:
    h = int(input())
    if h == 0:break
    mp = [list(map(int, input().split())) for _ in range(h)]
    game = Game(mp, h)
    game.run()
    print(game.score)

Solution (Python):

while 1:
    h=int(input())
    if h==0:
        break
    field=[]
    for i in range(h):
        field.insert(0,list(map(int,input().split())))
        field[0]+=[0]
    ans=0
    f=True
    while f:
        f=False
        for i in range(h):
            now=-1
            count=0
            for j in range(6):
                if now!=field[i][j] and count>=3:
                    for k in range(count):
                        field[i][j-1-k]=0
                    ans+=now*count
                    count=0
                    f=True if now!=0 else f
                elif now!=field[i][j]:
                    count=0
                now=field[i][j]
                count+=1
        for i in range(h-1):
            for j in range(5):
                if field[i][j]==0:
                    for k in range(i+1,h):
                        if field[k][j]!=0:
                            field[i][j],field[k][j]=field[k][j],field[i][j]
                            break
    print(ans)