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 &#8804; H &#8804; 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



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


Sample output:
36
38
99
0
72

Submission status: Accepted

Solution code:
from collections import Counter
while 1:
  H = int(input())
  if H == 0:
    exit()
    
  A = [[] for _ in range(5)]
  for i in range(H):
    tmp = list(map(int, input().split()))
    for j in range(5):
      A[j].append(tmp[j])
      
  for j in range(5):
    A[j] = A[j][::-1]
  
  ans = 0
  while 1:
    tmp = ans
    N = min([len(a) for a in A])
    for j in range(N):
      l = Counter([A[i][j] for i in range(5)])
      for k in range(10):
        if l[k] == 5:
          tmp += 5*k
          for i in range(5):
            A[i][j] = 'x'
          break
        elif A[0][j]==A[1][j]==A[2][j]==A[3][j]==k:
          tmp += 4*k
          for i in range(4):
            A[i][j] = 'x'
          break
        elif A[1][j]==A[2][j]==A[3][j]==A[4][j]==k:
          tmp += 4*k
          for i in range(1,5):
            A[i][j] = 'x'
          break
        elif A[0][j]==A[1][j]==A[2][j]==k:
          tmp += 3*k
          for i in range(3):
            A[i][j] = 'x'
          break
        elif A[1][j]==A[2][j]==A[3][j]==k:
          tmp += 3*k
          for i in range(1,4):
            A[i][j] = 'x'
          break
        elif A[2][j]==A[3][j]==A[4][j]==k:
          tmp += 3*k
          for i in range(2,5):
            A[i][j] = 'x'
          break
    if tmp == ans:
      break
    else:
      ans = tmp
      B = [[] for _ in range(5)]
      for i in range(5):
        for a in A[i]:
          if a != 'x':
            B[i].append(a)
      A = B
  print(ans)

Submission status: Accepted

Solution code:
while 1:
    n=int(input())
    if n==0:break
    A=[list(map(int,input().split())) for _ in range(n)]
    ans=0
    while 1:
        score=ans
        for i in range(n):
            cnt,num=0,A[i][0]
            for j in range(5):
                if A[i][j]==num:cnt +=1
                else:
                    if cnt>=3:
                        ans +=num*cnt
                        for k in range(cnt):A[i][j-k-1]=0
                    num=A[i][j]
                    cnt=1
                if j==4 and cnt>=3:
                    ans +=num*cnt
                    for k in range(cnt):A[i][j-k]=0
        B=[[-1 for _ in range(5)] for _ in range(n)]
        for i in range(5):
            cnt=n-1
            for j in range(n)[::-1]:
                if A[j][i]!=0:
                    B[j][i]=cnt
                    cnt -=1
        C=[[0 for _ in range(5)] for _ in range(n)]
        for i in range(5):
            for j in range(n):
                if B[j][i]!=-1:
                    C[B[j][i]][i]=A[j][i]
        A=C
        if score==ans:break
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    while True:
        H = I()
        if H==0:
            break
        else:
            s = [LI() for _ in range(H)]

            score = 0
            while True:
                # 消滅判定
                score_tmp = 0
                for i in range(H):
                    prev = 0
                    cnt = 1
                    for j in range(5):
                        if s[i][j]==prev:
                            cnt += 1
                        else:
                            if cnt>=3:
                                score_tmp += prev*cnt
                                for k in range(cnt):
                                    s[i][j-cnt+k] = 0
                            prev = s[i][j]
                            cnt = 1
                    if cnt>=3:
                        score_tmp += prev*cnt
                        for k in range(cnt):
                            s[i][j+1-cnt+k] = 0
                # print('s')
                # for i in s:
                #     print(i)
                if score_tmp==0:
                    break
                score += score_tmp

                # 落下処理
                # その石がどれだけ落下するかの算出
                drop = [[0]*5 for _ in range(H)]
                for i in range(5):
                    for j in range(H-1):
                        drop[H-j-2][i] = drop[H-j-1][i] + (1 if s[H-j-1][i]==0 else 0)
                # print('drop')
                # for i in drop:
                #     print(i)
                
                # 落下先にコピー
                for i in range(5):
                    for j in range(H):
                        if drop[H-j-1][i]!=0:
                            s[H-j-1+drop[H-j-1][i]][i] = s[H-j-1][i]
                            s[H-j-1][i] = 0
                # print('dropped s')
                # for i in s:
                #     print(i)

            print(score)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1193&lang=jp
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

def main():
    ans = []
    while True:
        H = int(readline())
        if H == 0:
            break

        c = [[int(i) for i in readline().split()] for _ in range(H)]
        seq = [[1] for _ in range(H)]
        ans_tmp = [0]
        
        score = 0
        while True:
            # 消す
            for i, line in enumerate(c):
                for j in range(1,5):
                    if line[j] == line[j-1]:
                        seq[i][-1] += 1
                    else:
                        seq[i].append(1)
            
                acc = -1
                for s in seq[i]:
                    acc += s
                    if s >= 3:
                        score += s * line[acc]
                        for j in range(acc - s + 1, acc + 1):
                            line[j] = 0
                seq[i] = [1]

            for i in reversed(range(H)):
                for j in range(5):
                    if c[i][j] == 0:
                        for h in reversed(range(i)):
                            if c[h][j] != 0:
                                c[h][j], c[i][j] = c[i][j], c[h][j]
                                break

            ans_tmp.append(score)
            if ans_tmp[-1] == ans_tmp[-2]:
                ans.append(ans_tmp[-1])
                break

    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
while True:
    H = int(input())
    if H==0:
        exit()
    board = [[0]*5 for _ in range(H+1)]
    for i in range(1,H+1):
        board[i] = list(map(int, input().split()))
    board = board[::-1]
    change = True
    score = 0
    while change==True:
        change = False
        for i in range(H-1,-1,-1):
            if len(set(board[i]))==1 and board[i][0]>0:
                score += sum(board[i])
                change = True
                for j in range(i,H):
                    board[j] = board[j+1]
            elif len(set(board[i][:4]))==1 and board[i][:4][0]>0:
                score += sum(board[i][:4])
                change = True
                for j in range(i,H):
                    board[j][:4] = board[j+1][:4]
            elif len(set(board[i][1:]))==1 and board[i][1:][0]>0:
                score += sum(board[i][1:])
                change = True
                for j in range(i,H):
                    board[j][1:] = board[j+1][1:]
            elif len(set(board[i][:3]))==1 and board[i][:3][0]>0:
                score += sum(board[i][:3])
                change = True
                for j in range(i,H):
                    board[j][:3] = board[j+1][:3]
            elif len(set(board[i][1:4]))==1 and board[i][1:4][0]>0:
                score += sum(board[i][1:4])
                change = True
                for j in range(i,H):
                    board[j][1:4] = board[j+1][1:4]
            elif len(set(board[i][2:]))==1 and board[i][2:][0]>0:
                score += sum(board[i][2:])
                change = True
                for j in range(i,H):
                    board[j][2:] = board[j+1][2:]
    print(score)

Submission status: Accepted

Solution code:

def solve():
    cnt = -1
    while 1:
        cnt += 1
        H = int(input())
        if H==0:
            break
        puzzle = [list(map(int, input().split())) for _ in range(H)]
        ans = 0
        while True:
            flg = True
            for i, row in enumerate(puzzle):
                if len(set(row))>=4:
                    continue
                streak = [-1, 1]
                for j, c in enumerate(row):
                    if c==-1:
                        streak[0] = -1
                        streak[1] = 1
                        continue
                    if c==streak[0]:
                        streak[1]+=1
                        if streak[1]==3:
                            flg = False
                            ans += c*3
                            puzzle[i][j-2:j+1] = [-1]*3
                        elif streak[1]>=4:
                            ans += c
                            puzzle[i][j] = -1
                    else:
                        streak[0] = c
                        streak[1] = 1
            for i, row in enumerate(puzzle[::-1]):
                if i==H-1:
                    break
                for j, c in enumerate(row):
                    if c==-1:
                        for h in range(H-i-1):
                            if puzzle[(H-i-1)-h-1][j]!=-1:
                                puzzle[-i-1][j] = puzzle[(H-i-1)-h-1][j]
                                puzzle[(H-i-1)-h-1][j] = -1
                                break
            if flg:
                print(ans)
                break

solve()

Submission status: Accepted

Solution code:

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

    p = 0
    fin = 0
    turn = 1
    while fin==0:
        #[print(*puyo[i]) for i in range(h)]
        fin = 1
        for i in range(h):
            cnt = 1
            for j in range(1, 5):
                if puyo[i][j-1] == puyo[i][j] and puyo[i][j]>0:
                    cnt += 1
                else:
                    if cnt>=3:
                        p += cnt * puyo[i][j-1]
                        for k in range(cnt):
                            puyo[i][j-k-1] = -1
                            fin = 0
                    cnt = 1
                if j==4:
                    if cnt>=3:
                        p += cnt * puyo[i][j-1]
                        for k in range(cnt):
                            puyo[i][j-k] = -1
                            fin = 0
        #print('after remove')
        #[print(*puyo[i]) for i in range(h)]              
        for i in range(5):
            d_fin = 0
            while d_fin==0:
                d_fin = 1
                for j in range(h-1, 0, -1):
                    if puyo[j][i]==-1 and puyo[j-1][i]>0:
                        puyo[j][i] = puyo[j-1][i]
                        puyo[j-1][i] = -1
                        d_fin = 0
        #print(f'turn {turn}')
        turn += 1
    print(p)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
import sys
import math
import string
import collections
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = 10 ** 18
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

H = int(input())
while H != 0:
    table = [list(map(int, input().split())) for _ in range(H)]
    prev_ans = -1
    ans = 0
    while ans != prev_ans:
        prev_ans = ans
        for i in range(H):
            for j in range(3):
                if table[i][j] != -1:
                    if table[i][j] == table[i][j + 1] == table[i][j + 2]:
                        for l in range(j + 2, 5):
                            if table[i][j] != table[i][l]:
                                ans += (l - j) * table[i][j]
                                for k in range(j, l):
                                    table[i][k] = -1
                                break
                            elif l == 4:
                                ans += (l - j + 1) * table[i][j]
                                for k in range(j, 5):
                                    table[i][k] = -1
                                break
        for i in range(H - 2, -1, -1):
            for j in range(5):
                if table[i][j] != -1:
                    if table[i + 1][j] == -1:
                        for l in range(i + 1, H):
                            if table[l][j] != -1:
                                table[l - 1][j] = table[i][j]
                                for k in range(i, l - 1):
                                    table[k][j] = -1
                                break
                            elif l == H - 1:
                                table[l][j] = table[i][j]
                                table[i][j] = -1
                                break

    print(ans)
    H = int(input())

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
                    #print (a[i][j])
                    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 (a)
    print (ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from inspect import currentframe


def debug_print(s):
    # 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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

Solution code:
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)
                    # 消したところを0に書き換える
                    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)
            # 消したところを0に書き換える
            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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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(field)
        print(score)

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