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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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())

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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=[[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]]
    a.reverse()
#    print(a)
    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))
#        print(dq)
        if len(dq)==0 :
            break
        while dq:
            hi,j,k=dq.popleft()
#            print("1:",a)
            for jj in range(j,j+k):
                a[hi][jj]=0
#        print("2:",a)
        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(a)
    print(p)

Submission status: Accepted

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

    # 下が0のマスだったら落ちる
    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')

Submission status: Accepted

Solution code:
# https://onlinejudge.u-aizu.ac.jp/problems/1193
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
        # print('-------')
        # for row in M:
        #     print(*row)
        # print('--drop-----')
        drop(M)
        # for row in M:
        # print(*row)
        # print('-------')
    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)

Submission status: Accepted

Solution code:
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)
    #print(lst)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


def cal(board):
    H = len(board)
    gain = 0
    tmp = [1]*5
    for row in board:
        for i in range(1, 5):
            tmp[i] = tmp[i-1] * (row[i-1] == row[i]) + 1
        for i in range(4, -1, -1):
            if tmp[i] >= 3:
                gain += row[i] * tmp[i]
                for j in range(i, i-tmp[i], -1):
                    row[j] = 0
                break

    for col in range(5):
        i = H-1
        for row in board[::-1]:
            if row[col]:
                board[i][col] = row[col]
                i -= 1
        for i in range(i, -1, -1):
            board[i][col] = 0

    return gain


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

    board = []
    for _ in [0]*H:
        *line, = map(int, input().split())
        board.append(line)

    score = 0
    while True:
        gain = cal(board)
        if gain == 0:
            break
        score += gain
    print(score)

Submission status: Accepted

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

while True:
    n = int(input())
    if n == 0:
        sys.exit()
    puzzle = [[] for _ in range(5)]
    # puzzle input
    for i in range(n):
        for j, stone in enumerate(list(map(int, input().split()))):
            puzzle[j].insert(0, stone)
            # puzzle[j].append(stone)
    tmp_score = 10
    ans = 0
    while tmp_score != 0:
        tmp_score = 0
        for i in range(n - 1, -1, -1):
        #for i in range(0, n):
            flg = False
            for left in range(3):
                for right in range(4, 1 + left, -1):
                        tmp_list = []
                        for idx in range(left, right+1):
                            try:
                                tmp_list.append(puzzle[idx][i])
                            except:
                                tmp_list.append(0)
                        if len(set(tmp_list)) == 1 and not (0 in tmp_list):
                            tmp_score += sum(tmp_list)
                            flg = True
                            # puzzle削除
                            for idx in range(left, right+1):
                                try:
                                    puzzle[idx].pop(i)
                                except:
                                    pass
                            break
                if flg:
                    break
        ans += tmp_score

    print(ans)

Submission status: Accepted

Solution code:
def CDP(h,w,k):
  q=[]
  ans=0
  d=-1
  m=0
  while True:
    if d==ans:break
    d=ans
    for i in range(h):
      cnt=0
      for j in range(w-1):
        if a[j][i]==a[j+1][i]:cnt+=1
        else:
          if cnt>=k-1:
            q.append((j-cnt,i,cnt+1))
          cnt=0
      if cnt>=k-1:
        q.append((w-cnt-1,i,cnt+1))      
    while q:
      j,i,cnt=q.pop()
      for c in range(cnt):
        ans+=a[j+c].pop(i)
        a[j+c].append(0)
  return ans

while True:
  h=int(input())
  if h==0:break
  b=[list(i[::-1]) for i in zip(*[input().split() for _ in range(h)])]
  a=[[int(s) for s in strs] for strs in b]
  print(CDP(h,5,3))

Submission status: Accepted

Solution code:
class Puzzle():
  def __init__(self, mat, N):
    self.mat = mat
    self.h = N
    self.score = 0

  def calc(self):
    tmp_score = self.score

    for i in range(self.h):
      for j in range(3):
        if self.mat[i][j] > 0:
          # 5,2
          for k in range(5, 2, -1):
            if j+k <= 7 and k-j >= 3:
              s = set(self.mat[i][j:k])
              if len(s) == 1 and -1 not in s:
                tmp_score += list(s)[0] * (k-j)
                for l in range(j, k):
                  self.mat[i][l] = -1
                break

    if self.score >= tmp_score:
      return False
    else:
      self.score = tmp_score
      return True

  def flatten(self):
    pivot_mat = []
    for i in range(5):
      row = []
      for j in range(self.h):
        if self.mat[j][i] != -1:
          row.append(self.mat[j][i])

      short = self.h - len(row)
      if short > 0:
        row.reverse()
        for k in range(short):
          row.append(-1)
        row.reverse()
      
      pivot_mat.append(row)

    mat = [ [-1]*5 for i in range(self.h) ]
    for i in range(self.h):
      for j in range(5):
        mat[i][j] = pivot_mat[j][i]

    self.mat = mat

while True:
  h = int(input())
  if h==0: exit()
  mat = []
  for _ in range(h):
    mat.append(list(map(int,input().split())))
  puzzle = Puzzle(mat, h)

  while True:
    if puzzle.calc():
      puzzle.flatten()
    else:
      break

  print(puzzle.score)

Submission status: Accepted

Solution code:
def move(board): # 空きを埋める関数
    board = [list(x) for x in zip(*board)]
    for i in range(len(board)):
        row = board[i]
        row = [i for i in row if i!=0]
        n = len(board[i]) - len(row)
        row.extend([0]*n)
        board[i] = row
    board = [list(x) for x in zip(*board)]
    return board

ls_ans = []
while(1):
    ans = 0
    H = int(input())
    if H==0:
        break
    board = []
    for h in range(H):
        C = list(map(int,input().split()))
        board.append(C)
    board = board[::-1]
    for t in range(H):
        for h in range(H):
            C = board[h]
            changed = set()
            old_c = ''
            oldold_c = ''
            streak = 0
            for i,c in enumerate(C):
                if c == old_c and c == oldold_c:
                    if streak == 0:
                        streak += 3*c
                        C[i] = C[i-1] = C[i-2] = 0
                    else:
                        streak += c
                        C[i] = 0
                else:
                    ans += streak
                    streak = 0
                oldold_c = old_c
                old_c = c
            ans += streak
            board[h] = C
        board = move(board)
    ls_ans.append(ans)

for ans in ls_ans:
    print (ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

while True:
    H = int(input())
    if H == 0:
        break
    B = [0] * H
    for i in range(H):
        B[i] = list(map(int, input().split()))
    W = len(B[i])

    score = 0
    while True:
        # erase step
        for i in range(H):
            start = 0
            while start < W:
                count = 1
                while start + count < W and B[i][start] == B[i][start + count]:
                    count += 1
                if count >= 3:
                    score += B[i][start] * count
                    for j in range(start, start + count):
                        B[i][j] = 0
                start += count
        # drop step
        updated = False
        for i in range(H - 1, -1, -1):
            for j in range(W - 1, -1, -1):
                if B[i][j] != 0:
                    continue
                new_col = []
                for k in range(i, -1, -1):
                    if B[k][j] == 0:
                        continue
                    new_col.append(B[k][j])
                l = 0
                for k in range(i, -1, -1):
                    if l >= len(new_col):
                        B[k][j] = 0
                    else:
                        B[k][j] = new_col[l]
                        updated = True
                    l += 1
        if not updated:
            break
    print(score)

Submission status: Accepted

Solution code:
while True:
    H = int(input())
    if H == 0:
        exit()
    L = [input().split() for _ in range(H)]
    L1 = list(reversed([l[0] for l in L]))
    L2 = list(reversed([l[1] for l in L]))
    L3 = list(reversed([l[2] for l in L]))
    L4 = list(reversed([l[3] for l in L]))
    L5 = list(reversed([l[4] for l in L]))
    ans = 0
    while True:
        changed = False
        for i in range(H):
            if L1[i] != 'X' and L1[i] == L2[i] == L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 5*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
            elif L1[i] != 'X' and L1[i] == L2[i] == L3[i] == L4[i]:
                changed = True
                ans += 4*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
            elif L2[i] != 'X' and L2[i] == L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 4*int(L2[i])
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
            elif L1[i] != 'X' and L1[i] == L2[i] == L3[i]:
                changed = True
                ans += 3*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
            elif L2[i] != 'X' and L2[i] == L3[i] == L4[i]:
                changed = True
                ans += 3*int(L2[i])
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
            elif L3[i] != 'X' and L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 3*int(L3[i])
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
        if not changed:
            break
        L1 = list(filter(lambda x: x!='X',L1)) + ['X']*L1.count('X')
        L2 = list(filter(lambda x: x!='X',L2)) + ['X']*L2.count('X')
        L3 = list(filter(lambda x: x!='X',L3)) + ['X']*L3.count('X')
        L4 = list(filter(lambda x: x!='X',L4)) + ['X']*L4.count('X')
        L5 = list(filter(lambda x: x!='X',L5)) + ['X']*L5.count('X')
    print(ans)

Submission status: Accepted

Solution code:
H = int(input())

while H:
  Ali = [list(map(int,input().split())) for _ in range(H)]
  score = 0
  while True:
    sc = score
    for i in range(H):
      Row = Ali[i]
      #5つ
      if Row[0] == Row[1] == Row[2] == Row[3] == Row[4]:
        score += Row[0]*5
        Ali[i][0] = Ali[i][1] = Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
      
      #4つ
      if Row[0] == Row[1] == Row[2] == Row[3]:
        score += Row[0]*4
        Ali[i][0] = Ali[i][1] = Ali[i][2] = Ali[i][3] = 0
      
      if Row[1] == Row[2] == Row[3] == Row[4]:
        score += Row[1]*4
        Ali[i][1] = Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
      
    #3つ
      if Row[0] == Row[1] == Row[2]:
        score += Row[0]*3
        Ali[i][0] = Ali[i][1] = Ali[i][2] = 0
      
      if Row[1] == Row[2] == Row[3]:
        score += Row[1]*3
        Ali[i][1] = Ali[i][2] = Ali[i][3] = 0
      
      if Row[2] == Row[3] == Row[4]:
        score += Row[2]*3
        Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
        
    if sc == score:
      break
      
    #落としていく処理
    #下から上に見ていく
    for i in range(1,H+1):
      for j in range(0,5):
        if Ali[-i][j] == 0:
          for k in range(i+1,H+1):
            if Ali[-k][j] != 0:
              Ali[-i][j] = Ali[-k][j]
              Ali[-k][j] = 0
              break
              
  print(score)
  H = int(input())

Submission status: Accepted

Solution code:
while(1):
    h = int(input())
    if not h:
        break
    a = [[] for j in range(h)]
    for i in range(h):
        a[i] = [int(i) for i in input().split()]
    ans = 0
    disap = True
    fall = True
    while(disap):
        while(disap):
            disap = False
            for i in range(h):
                if a[i][0] and all([a[i][k] == a[i][k+1] for k in range(4)]):
                    ans += a[i][0]*5
                    for k in range(5):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][0] and all([a[i][k] == a[i][k+1] for k in range(3)]):
                    ans += a[i][0]*4
                    for k in range(4):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][1] and all([a[i][k+1] == a[i][k+2] for k in range(3)]):
                    ans += a[i][1]*4
                    for k in range(4):
                        a[i][k+1] = 0
                    disap = True
                    fall = True
                elif a[i][0] and all([a[i][k] == a[i][k+1] for k in range(2)]):
                    ans += a[i][0]*3
                    for k in range(3):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][1] and all([a[i][k+1] == a[i][k+2] for k in range(2)]):
                    ans += a[i][1]*3
                    for k in range(3):
                        a[i][k+1] = 0
                    disap = True
                    fall = True
                elif a[i][2] and all([a[i][k+2] == a[i][k+3] for k in range(2)]):
                    ans += a[i][2]*3
                    for k in range(3):
                        a[i][k+2] = 0
                    disap = True
                    fall = True
        while(fall):
            fall = False
            for i in range(1, h):
                for j in range(5):
                    if a[i][j] == 0 and a[i-1][j]:
                        a[i][j], a[i-1][j] = a[i-1][j], a[i][j]
                        fall = True
                        disap = True
    print(ans)

Submission status: Accepted

Solution code:
while True:
    H = int(input())
    if H == 0:
        break
    squares = [list(map(int, input().split())) for _ in range(H)]
    score = 0
    while True:
        deleted = False
        for i in range(H):
            for j in range(5, 2, -1):
                for k in range(5 - j + 1):
                    deletable = True
                    first_num = squares[i][k]
                    if first_num == 0:
                        continue
                    for num in squares[i][k + 1:k + j]:
                        if first_num != num:
                            deletable = False
                            break
                    if deletable:
                        score += first_num * j
                        squares[i][k:k + j] = [0] * j
                        deleted = True
        # print(squares)
        if deleted:
            while True:
                not_falled = True
                # 下からやっていった方がいい。また、0行目はやる必要なし
                for i in range(H - 1, 0, -1):
                    for k, num in enumerate(squares[i]):
                        if num == 0 and squares[i - 1][k] != 0:
                            squares[i - 1][k], squares[i][k] = squares[i][k], squares[i - 1][k]
                            not_falled = False
                if not_falled:
                    break
        else:
            break
    print(score)
    # print(squares)

Submission status: Accepted

Solution code:
def puyo_one(A):
  ans = 0
  now = 1
  for i in range(1, 5):
    if A[i] == A[i - 1]:
      now += 1
    else:
      if now >= 3:
        ans += now * A[i - 1]
      now = 1
  return ans

def puyo(A):#A:配列
  p = 0#消せるものがなくなったらp=1とし、ansを返す
  ans = 0
  while p == 0:
    this = 0
    #ぷよを消して加点
    for i in range(len(A)):
      now = 1 
      for j in range(1, 5):
        if (A[i][j] == A[i][j - 1]) and (A[i][j] != 0):
          now += 1
        else:
          if now >= 3:
            this = 1
            ans += A[i][j - 1] * now 
            for k in range(j - now, j):
              A[i][k] = 0
          now = 1
      if now >= 3:
        this = 1
        ans += A[i][j - 1] * now 
        for k in range(j - now + 1, j + 1):
          A[i][k] = 0
    #print(A, this, ans)
    #一回も消してない場合
    if this == 0:
      p = 1
    #残ったぷよを落とす
    #落とすところ
    N = len(A)
    for i in range(1, N + 1):
      for j in range(5):
        if (A[N - i][j] == 0) and (i != N):
          k = 1
          while (A[N - i - k][j] == 0) and (k + i < N):
            k += 1
          A[N - i][j] = A[N - i - k][j]
          A[N - i - k][j] = 0
    #一つもない行がある時、その行ごと消す
    q = 0
    while q == 0:
      if [0, 0, 0, 0, 0] in A:
        A.pop(A.index([0, 0, 0, 0, 0]))
      else:
        q = 1
    #print(A)
  return ans

l = 0
while l == 0:
  H = int(input())
  if H == 0:
    quit()
  else:
    A = [0] * H
    for i in range(H):
      A[i] = list(map(int, input().split()))
      #print(A)
    print(puyo(A))