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: Wrong Answer

Solution code:
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:
                        data = data.replace(check(d, i), check('0', i))
                        removed = True
                        score += int(d) * i
                        break
        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)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
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):
                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 = map(list, zip_longest(*fieldT))

    print(score)

Submission status: Wrong Answer

Solution code:
def calc(puzzle,H,score):
    flag=False
    for i in range(H-1,-1,-1):
        stones=[]
        for j in range(5):
            now=puzzle[j][i]
            if (len(stones)==0 or stones[-1]==now) and now!=0: stones.append(now)
            elif len(stones)<3: stones=[now]
        if len(stones)>2:
            flag=True
            score+=sum(stones)
            for j in range(5):
                if puzzle[j][i]==stones[0]: 
                    puzzle[j].pop(i)
                    puzzle[j].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: Wrong Answer

Solution code:
def calc(puzzle,H,score):
    flag=False
    for i in range(H-1,-1,-1):
        stones=[]
        for j in range(5):
            now=puzzle[j][i]
            if (len(stones)==0 or stones[-1]==now) and now!=0: stones.append(now)
            elif len(stones)<3: stones=[now]
            else: break
        if len(stones)>2:
            flag=True
            score+=sum(stones)
            for j in range(5):
                if puzzle[j][i]==stones[0]: 
                    puzzle[j].pop(i)
                    puzzle[j].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: Wrong Answer

Solution code:
def calc(puzzle,H,score):
    flag=False
    for i in range(H-1,-1,-1):
        stones=[]
        for j in range(5):
            now=puzzle[j][i]
            if (len(stones)==0 or stones[-1]==now) and now!=0: stones.append(now)
            elif len(stones)<3: stones=[now]
            else: break
        if len(stones)>2:
            flag=True
            score+=sum(stones)
            stone=stones[0]
            for j in range(5):
                now=puzzle[j][i]
                if now==stone:
                    if (j<4 and now==puzzle[j+1][i]) or (j>0 and now==puzzle[j-1][i]):
                        puzzle[j].pop(i)
                        puzzle[j].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: Wrong Answer

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
						break
					k += 1
					j = k - 1
				if co >= 2:
					re = True
					s += (co+1)*cell
					for l in range(5):
						if l >= p and l < k+2:
							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(ppp)
	print(s)

	s = 0

	a = int(input())

Submission status: Wrong Answer

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
						break
					k += 1
					j = k - 1
				if co >= 2:
					re = True
					s += (co+1)*cell
					for l in range(5):
						if l >= p and l < k+1:
							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):
		print(ppp)
		mo(ppp,a)
	print(s)

	s = 0

	a = int(input())

Submission status: Wrong Answer

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
						break
					k += 1
					j = k - 1
				if co >= 2:
					re = True
					s += (co+1)*cell
					for l in range(5):
						if l >= p and l <= k:
							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: Wrong Answer

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
						break
					k += 1
					j = k
				if co >= 2:
					re = True
					s += (co+1)*cell
					for l in range(5):
						if l >= p and l <= k:
							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: Wrong Answer

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(ppp)
	print(s)

	s = 0

	a = int(input())

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from functools import lru_cache


def DEBUG(*args): pass # print('@', *args)


@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 == '#' else int(x), data.split()))
        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 == '#' else int(x), data.split())))
        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)

Submission status: Accepted

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

Submission status: Accepted

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

            #for y in ban:
            #    print(y)
            #print()

            if not flag:
                break

        print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
        # for x in field: print(*map(lambda x: "X" if x == None else x, x))
        # print("===========")
    print(score)