Problem:


Biased Dice

Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice.  His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane.  The dice fall onto the plane or dice already there, without rotating, and may roll and fall according to their property.  Then he observes and records the status of the stack formed on the plane, specifically, how many times each number appears on the faces visible from above. All the dice have the same size and their face numbering is identical, which we show in Figure C-1.

Figure C-1: Numbering of a die

The dice have very special properties, as in the following.

(1) Ordinary dice can roll in four directions, but the dice used in this experiment never roll in the directions of faces 1, 2 and 3; they can only roll in the directions of faces 4, 5 and 6.  In the situation shown in Figure C-2, our die can only roll to one of two directions.

Figure C-2: An ordinary die and a biased die

(2) The die can only roll when it will fall down after rolling, as shown in Figure C-3.  When multiple possibilities exist, the die rolls towards the face with the largest number among those directions it can roll to.

Figure C-3: A die can roll only when it can fall

(3) When a die rolls, it rolls exactly 90 degrees, and then falls straight down until its bottom face touches another die or the plane, as in the case [B] or [C] of Figure C-4.

(4) After rolling and falling, the die repeatedly does so according to the rules (1) to (3) above.

Figure C-4: Example stacking of biased dice

For example, when we drop four dice all in the same orientation, 6 at the top and 4 at the front, then a stack will be formed as shown in Figure C-4.

Figure C-5: Example records

After forming the stack, we count the numbers of faces with 1 through 6 visible from above and record them.  For example, in the left case of Figure C-5, the record will be "0 2 1 0 0 0", and in the right case, "0 1 1 0 0 1".

Input

The input consists of several datasets each in the following format.

n 

t1  f1

t2  f2

...                                

tn  fn

Here, n (1 ≤ n ≤ 100) is an integer and is the number of the dice to be dropped.  ti and fi (1 ≤ ti, fi ≤ 6) are two integers separated by a space and represent the numbers on the top and the front faces of the i-th die, when it is released, respectively.

The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output six integers separated by a space. The integers represent the numbers of faces with 1 through 6 correspondingly, visible from above. There may not be any other characters in the output.

Sample Input

4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0

Output for the Sample Input

0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0



Sample input:
4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0


Sample output:
0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0

Submission status: Accepted

Solution code:
#! cat input | python3 main.py
def debug():
    for X in field[size//2:] + field[:size//2]:
        print(X[size//2:], X[:size//2])

dice_data = [[],
        [4, 2, 3, 5],
        [4, 6, 3, 1],
        [6, 5, 1, 2],
        [1, 5, 6, 2],
        [4, 1, 3, 6],
        [4, 5, 3, 2],
        ]
def dice(t, f):
    i = dice_data[t].index(f)
    return [dice_data[t][x%4] for x in range(i, i + 4)]

size = 6
move = [[-1, 0], [0, 1], [1, 0], [0, -1]]

def drop(t, f, nowl, nowr):
    target = list(map(lambda x: x > 3, dice(t, f)))
    now = [nowl, nowr]
    
    now_field = field[now[0]][now[1]]
    for i, tg in enumerate(target):
        if tg:
            nb_field = field[now[0] + move[i][0]][now[1] + move[i][1]]
            if nb_field[1] >= now_field[1]:
                target[i] = False
    for i, v in sorted(enumerate(dice(t, f)), key=lambda x: x[1], reverse=True):
        if target[i]:
            if i == 0:
                f = t
            elif i == 2:
                f = 7 - t
            t = 7 - v
            drop(t, f, now[0] + move[i][0], now[1] + move[i][1])
            break
    else:
        change = field[now[0]][now[1]]
        change[0] = t
        change[1] += 1

while True:
    n = int(input())
    if not n: break
    field = [[[0, 0] for i in range(size)] for j in range(size)]

    tfs = [list(map(int, input().split())) for x in range(n)]
    for t, f in tfs:
        drop(t, f, 0, 0)
    cnt = [0 for x in range(7)]
    for row in field:
        for cell in row:
            cnt[cell[0]] += 1
    print(*cnt[1:])

Submission status: Accepted

Solution code:
class RollDir:
    def __init__(self, d, w):
        self.d = d
        self.w = w

    def __str__(self):
        return "Roll dir: {}, weight: {}".format(self.d, self.w)

    @classmethod
    def create(cls, d, w):
        if w == 6 or w == 5 or w == 4:
            return cls(d, w)
        else:
            return None

class Dice:
    def __init__(self, t, f):
        self.top = t
        self.bot = 7 - t

        if t == 1:
            arr = [2, 3, 5, 4]
        elif t == 6:
            arr = [5, 3, 2, 4]
        elif t == 2:
            arr = [3, 1, 4, 6]
        elif t == 5:
            arr = [3, 6, 4, 1]
        elif t == 3:
            arr = [6, 5, 1, 2]
        elif t == 4:
            arr = [1, 5, 6, 2]

        idx = arr.index(f)
        self.front = arr[idx]
        self.right = arr[(idx + 1) % 4]
        self.back = arr[(idx + 2) % 4]
        self.left = arr[(idx + 3) % 4]

    def roll(self, direction):
        if direction == 'N':
            temp = self.top
            self.top = self.front
            self.front = self.bot
            self.bot = self.back
            self.back = temp
        elif direction == 'E':
            temp = self.top
            self.top = self.left
            self.left = self.bot
            self.bot = self.right
            self.right = temp
        elif direction == 'W':
            temp = self.top
            self.top = self.right
            self.right = self.bot
            self.bot = self.left
            self.left = temp
        elif direction == 'S':
            temp = self.top
            self.top = self.back
            self.back = self.bot
            self.bot = self.front
            self.front = temp

    def getRollDir(self):
        arr = []
        roll = RollDir.create('S', self.front)
        if roll != None:
            arr.append(roll)
        roll = RollDir.create('E', self.right)
        if roll != None:
            arr.append(roll)
        roll = RollDir.create('N', self.back)
        if roll != None:
            arr.append(roll)
        roll = RollDir.create('W', self.left)
        if roll != None:
            arr.append(roll)

        return sorted(arr, key=lambda x: x.w ,reverse=True)
        
    def __str__(self):
        return "Top: {}   Front: {}   Left: {}   Right: {}" \
            .format(self.top, self.front, self.left, self.right)

class Cell:
    def __init__(self):
        self.height = 0
        self.val = None

class Grid:
    def __init__(self):
        self.cells = {}

    def drop(self, dice, x, y):
        if (x, y) not in self.cells:
            self.cells[ (x, y) ] = Cell()
        cell = self.cells[ (x, y) ]

        diceRollDirs = dice.getRollDir()
        gridRollDirs = self.getRollableDir(x, y)

        didRoll = False
        for roll in diceRollDirs:
            if roll.d in gridRollDirs:
                direction = roll.d
                dice.roll(direction)
                rollCoord = self.getRollCoord(x, y, direction)
                self.drop(dice, rollCoord[0], rollCoord[1])
                didRoll = True
                break
        
        if not didRoll:
            cell.height += 1
            cell.val = dice.top

    def getRollableDir(self, x, y):
        if (x, y) not in self.cells:
            self.cells[(x, y)] = Cell()
        cell = self.cells[(x, y)]

        arr = []
        if cell.height == 0:
            return []
        if (x-1, y) not in self.cells or self.cells[(x-1, y)].height < cell.height:
            arr.append('N')
        if (x, y+1) not in self.cells or self.cells[(x, y+1)].height < cell.height:
            arr.append('E')
        if (x, y-1) not in self.cells or self.cells[(x, y-1)].height < cell.height:
            arr.append('W')
        if (x+1, y) not in self.cells or self.cells[(x+1, y)].height < cell.height:
            arr.append('S')
        return arr

    def getRollCoord(self, x, y, d):
        if d == 'N':
            return (x-1, y)
        elif d == 'E':
            return (x, y+1)
        elif d == 'W':
            return (x, y-1)
        elif d == 'S':
            return (x+1, y)

    def countVals(self):
        count = [0, 0, 0, 0, 0, 0]
        for coord in self.cells:
            cell = self.cells[coord]
            count[ cell.val - 1 ] += 1
        return count


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

        grid = Grid()
        for _ in range(N):
            t, f = [ int(x) for x in list(filter(lambda x: x != '', \
                input().strip().split(' '))) ]
            dice = Dice(t, f)
            grid.drop(dice, 0, 0)

        print(" ".join(list(map(str, grid.countVals()))))

Submission status: Accepted

Solution code:
def get_num(top):  # 転がす番号の候補を決める
    if top == 1:
        return [5, 4]
    elif top == 2:
        return [6, 4]
    elif top == 3:
        return [6, 5]
    elif top == 4:
        return [6, 5]
    elif top == 5:
        return [6, 4]
    elif top == 6:
        return [5, 4]


def get_dir(num, front, top):  # 転がる向きを決める
    if num == front:
        return ["F", num]
    elif num == 7 - front:
        return ["B", num]
    # print(num, front)
    if num == 4:
        if (front == 1 and top == 5) or (front == 5 and top == 6) or (front == 6 and top == 2) or (front == 2 and top == 1):
            return ["L", num]
        elif (front == 5 and top == 1) or (front == 6 and top == 5) or (front == 2 and top == 6) or (front == 1 and top == 2):
            return ["R", num]

    if num == 5:
        if (front == 1 and top == 3) or (front == 3 and top == 6) or (front == 6 and top == 4) or (front == 4 and top == 1):
            return ["L", num]
        elif (front == 3 and top == 1) or (front == 6 and top == 3) or (front == 4 and top == 6) or (front == 1 and top == 4):
            return ["R", num]

    if num == 6:
        if (front == 2 and top == 4) or (front == 4 and top == 5) or (front == 5 and top == 3) or (front == 3 and top == 2):
            return ["L", num]
        elif (front == 4 and top == 2) or (front == 5 and top == 4) or (front == 3 and top == 5) or (front == 2 and top == 3):
            return ["R", num]


def can_roll(dir, nowi, nowj, maps):
    I = 0
    J = 0
    if dir == "F":
        I += 1
    if dir == "B":
        I -= 1
    if dir == "R":
        J += 1
    if dir == "L":
        J -= 1
    if maps[nowi][nowj][0] >= maps[nowi + I][nowj + J][0] + 1:
        return True
    return False


def roll(maps, nowi, nowj, top, front):
    roll_num = get_num(top)
    # print(roll_num, front, top)
    dir1_list = get_dir(roll_num[0], front, top)
    dir2_list = get_dir(roll_num[1], front, top)
    # print(dir1_list, dir2_list)
    dir1 = dir1_list[0]
    dir2 = dir2_list[0]
    # print(dir1, dir2)
    if can_roll(dir1, nowi, nowj, maps):
        # print(nowi, nowj, dir1, 7 - dir1_list[1])
        I = 0
        J = 0
        if dir1 == "F":
            I += 1
            front = top
        if dir1 == "B":
            I -= 1
            front = 7 - top
        if dir1 == "R":
            J += 1
        if dir1 == "L":
            J -= 1
        maps = roll(maps, nowi + I, nowj + J, 7 - dir1_list[1], front)
    elif can_roll(dir2, nowi, nowj, maps):
        # print(nowi, nowj, dir2, 7 - dir2_list[1])
        I = 0
        J = 0
        if dir2 == "F":
            I += 1
            front = top
        if dir2 == "B":
            I -= 1
            front = 7 - top
        if dir2 == "R":
            J += 1
        if dir2 == "L":
            J -= 1
        maps = roll(maps, nowi + I, nowj + J, 7 - dir2_list[1], front)
    else:
        maps[nowi][nowj][0] += 1
        maps[nowi][nowj][1] = top
    return maps

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

    maps = [[[0, 0] for _ in range(201)] for _ in range(201)]
    nowi = 100
    nowj = 100
    for i in range(n):
        t, f = map(int, input().split())
        maps = roll(maps, nowi, nowj, t, f)
    cnt = [0 for _ in range(6)]
    for i in range(len(maps)):
        for j in range(len(maps[i])):
            if maps[i][j][1]:
                cnt[maps[i][j][1] - 1] += 1
    for i in range(len(cnt)):
        cnt[i] = str(cnt[i])
    # print(maps[100])
    print(" ".join(cnt))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
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(): return list(sys.stdin.readline())[:-1]
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

#2005_c
"""
n = int(input())
k = list("mcxi")
for i in range(n):
    d = {"m":0,"c":0,"x":0,"i":0}
    a,b  = input().split()
    a = list(a)
    b = list(b)
    a.insert(0,1)
    b.insert(0,1)
    for j in range(1,len(a)):
        if a[j] in k:
            if a[j-1] in k:
                d[a[j]] += 1
            else:
                d[a[j]] += int(a[j-1])
    for j in range(1,len(b))[::-1]:
        if b[j] in k:
            if b[j-1] in k:
                d[b[j]] += 1
            else:
                d[b[j]] += int(b[j-1])
            if d[b[j]] >= 10:
                l = b[j]
                while d[l] >= 10:
                    d[l] -= 10
                    l = k[k.index(l)-1]
                    d[l] += 1
    for j in k:
        if d[j]:
            if d[j] == 1:
                print(j,end = "")
            else:
                print(str(d[j])+j,end = "")
    print()
"""

#2017_c
"""
while 1:
    h, w = map(int, input().split())
    if h == w == 0:
        break
    s = [list(map(int, input().split())) for i in range(h)]

    ans = 0
    for u in range(h):
        for d in range(u+2,h):
            for l in range(w):
                for r in range(l+2,w):
                    m = float("inf")
                    for i in range(u,d+1):
                        m = min(m,s[i][l],s[i][r])
                    for i in range(l,r+1):
                        m = min(m,s[u][i],s[d][i])
                    f = 1
                    su = 0
                    for i in range(u+1,d):
                        for j in range(l+1,r):
                            su += (m-s[i][j])
                            if s[i][j] >= m:
                                f = 0
                                break
                        if not f:
                            break
                    if f:
                        ans = max(ans,su)
    print(ans)
"""

#2016_c
"""
while 1:
    m,n = map(int, input().split())
    if m == n == 0:
        break
    ma = 7368791
    d = [0]*(ma+1)
    z = m
    for i in range(n):
        while d[z]:
            z += 1
        j = z
        while j <= ma:
            d[j] = 1
            j += z
    for j in range(z,ma+1):
        if not d[j]:
            print(j)
            break
"""

#2018_c
"""
def factorize(n):
    if n < 4:
        return [1,n]
    i = 2
    l = [1]
    while i**2 <= n:
        if n%i == 0:
            l.append(i)
            if n//i != i:
                l.append(n//i)
        i += 1
    l.append(n)
    l.sort()
    return l
while 1:
    b = int(input())
    if b == 0:
        break
    f = factorize(2*b)
    for n in f[::-1]:
        a = 1-n+(2*b)//n
        if a >= 1 and a%2 == 0:
            print(a//2,n)
            break
"""

#2010_c
"""
import sys
dp = [100]*1000000
dp_2 = [100]*1000000
dp[0] = 0
dp_2[0] = 0
for i in range(1,181):
    s = i*(i+1)*(i+2)//6
    for j in range(s,1000000):
        if dp[j-s]+1 < dp[j]:
            dp[j] = dp[j-s]+1
    if s%2:
        for j in range(s,1000000):
            if dp_2[j-s]+1 < dp_2[j]:
                dp_2[j] = dp_2[j-s]+1
while 1:
    m = int(sys.stdin.readline())
    if m == 0:
        break
    print(dp[m],dp_2[m])
"""

#2015_c
"""
from collections import deque
while 1:
    n = int(input())
    if n == 0:
        break
    s = [input() for i in range(n)]
    d = [s[i].count(".") for i in range(n)]
    m = max(d)
    c = [s[i][-1] for i in range(n)]
    q = deque()
    for i in range(1,m+1)[::-1]:
        j = 0
        while j < n:
            for k in range(j,n):
                if d[k] == i:break
            else:
                break
            j = k
            op = c[j-1]
            while j < n and d[j] == i:
                q.append(j)
                j += 1
            j = k
            if op == "+":
                k = 0
                while q:
                    x = q.pop()
                    k += int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            else:
                k = 1
                while q:
                    x = q.pop()
                    k *= int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            c[j-1] = k
    print(c[0])
"""

#2013_c
"""
from collections import defaultdict

def parse_expr(s,i):
    i += 1
    if s[i] == "[":
        q = []
        while s[i] != "]":
            e,i = parse_expr(s,i)
            q.append(e)
        return (calc(q),i+1)
    else:
        n,i = parse_num(s,i)
        return (calc([n]),i+1)

def parse_num(s,i):
    m = int(s[i])
    i += 1
    while f_num[s[i]]:
        m *= 10
        m += int(s[i])
        i += 1
    return (m,i)

def calc(q):
    if len(q) == 1:
        return (q[0]+1)//2
    q.sort()
    return sum(q[:len(q)//2+1])

f_num = defaultdict(lambda : 0)
for i in range(10):
    f_num[str(i)] = 1

n = int(input())
for i in range(n):
    s = input()
    print(parse_expr(s,0)[0])
"""

#2003_C
"""
while 1:
    w,h = LI()
    if w == h == 0:
        break
    s = SR(h)
    dp = [[0]*w for i in range(h)]
    for y in range(h):
        for x in range(w):
            if s[y][x].isdecimal():
                dp[y][x] = max(dp[y-1][x],dp[y][x-1])*10+int(s[y][x])
    ans = 0
    for i in dp:
        ans = max(ans,max(i))
    print(ans)
"""
#2008_C
"""def parse_formula(s,i):
    if s[i] == "-":
        i += 1
        e,i = parse_formula(s,i)
        return 2-e,i
    elif s[i] == "(":
        i += 1
        e1,i = parse_formula(s,i)
        op = s[i]
        i += 1
        e2,i = parse_formula(s,i)
        i += 1
        return calc(op,e1,e2),i
    else:
        return int(s[i]),i+1

def calc(op,a,b):
    if op == "*":
        return min(a,b)
    else:
        return max(a,b)

while 1:
    s = S()
    if s[0] == ".":
        break
    t = []
    f = defaultdict(int)
    for p in range(3):
        f["P"] = p
        for q in range(3):
            f["Q"] = q
            for r in range(3):
                f["R"] = r
                t.append([f[s[i]] if s[i] in "PQR" else s[i] for i in range(len(s))])
    ans = 0
    for s in t:
        if parse_formula(s,0)[0] == 2:
            ans += 1
    print(ans)
"""
#2011_C
"""
d = [(1,0),(-1,0),(0,1),(0,-1)]
def dfs(dep,s):
    global ans
    if dep == 5:
        b = bfs(s)
        m = 0
        for i in b:
            m += sum(i)
        ans = max(ans, m)
    else:
        if dep < 4:
            for i in range(6):
                b = bfs(s)
                dfs(dep+1,[[i+1 if b[y][x] else s[y][x] for x in range(w)] for y in range(h)])
        else:
            b = bfs(s)
            dfs(dep+1,[[c if b[y][x] else s[y][x] for x in range(w)] for y in range(h)])

def bfs(s):
    b = [[0]*w for i in range(h)]
    b[0][0] = 1
    q = deque([(0,0)])
    while q:
        y,x = q.popleft()
        for dy,dx in d:
            y_ = y+dy
            x_ = x+dx
            if 0 <= y_ < h and 0 <= x_ < w:
                if not b[y_][x_] and s[y_][x_] == s[0][0]:
                    b[y_][x_] = 1
                    q.append((y_,x_))
    return b

while 1:
    h,w,c = LI()
    if h == 0:
        break
    s = LIR(h)
    ans = 0
    dfs(0,s)
    print(ans)
"""
#2012_C
def make_dice(t,f):
    if t == 1:
        if f == 2:
            return [t,f,3,7-f,4,7-t]
        if f == 3:
            return [t,f,5,7-f,2,7-t]
        if f == 5:
            return [t,f,4,7-f,3,7-t]
        if f == 4:
            return [t,f,2,7-f,5,7-t]
    if t == 2:
        if f == 1:
            return [t,f,4,7-f,3,7-t]
        if f == 4:
            return [t,f,6,7-f,1,7-t]
        if f == 6:
            return [t,f,3,7-f,4,7-t]
        if f == 3:
            return [t,f,1,7-f,6,7-t]
    if t == 3:
        if f == 1:
            return [t,f,2,7-f,5,7-t]
        if f == 2:
            return [t,f,6,7-f,1,7-t]
        if f == 6:
            return [t,f,5,7-f,2,7-t]
        if f == 5:
            return [t,f,1,7-f,6,7-t]
    if t == 4:
        if f == 1:
            return [t,f,5,7-f,2,7-t]
        if f == 5:
            return [t,f,6,7-f,1,7-t]
        if f == 6:
            return [t,f,2,7-f,5,7-t]
        if f == 2:
            return [t,f,1,7-f,6,7-t]
    if t == 5:
        if f == 1:
            return [t,f,3,7-f,4,7-t]
        if f == 3:
            return [t,f,6,7-f,1,7-t]
        if f == 6:
            return [t,f,4,7-f,3,7-t]
        if f == 4:
            return [t,f,1,7-f,6,7-t]
    if t == 6:
        if f == 2:
            return [t,f,4,7-f,3,7-t]
        if f == 4:
            return [t,f,5,7-f,2,7-t]
        if f == 5:
            return [t,f,3,7-f,4,7-t]
        if f == 3:
            return [t,f,2,7-f,5,7-t]
dy = [0,-1,0,1,0,0]
dx = [0,0,1,0,-1,0]
def Set(s,dice):
    z,y,x = fall(s,dice,99,99)
    dir = check(s,z,y,x,dice)
    while dir:
        s[z][y][x] = 0
        dice = rotate(dice,dir)
        z,y,x = fall(s,dice,y+dy[dir],x+dx[dir])
        dir = check(s,z,y,x,dice)

def fall(s,dice,y,x):
    for z in range(100):
        if s[z][y][x] == 0:
            s[z][y][x] = dice[0]
            return z,y,x

def check(s,z,y,x,dice):
    if z == 0:
        return 0
    for c in (6,5,4):
        dir = dice.index(c)
        if s[z][y+dy[dir]][x+dx[dir]] == 0 and s[z-1][y+dy[dir]][x+dx[dir]] == 0 :
            return dir
    return 0

def rotate(dice,dir):
    if dir == 1:
        return [dice[3],dice[0],dice[2],dice[5],dice[4],dice[1]]
    if dir == 2:
        return [dice[4],dice[1],dice[0],dice[3],dice[5],dice[2]]
    if dir == 3:
        return [dice[1],dice[5],dice[2],dice[0],dice[4],dice[3]]
    else:
        return [dice[2],dice[1],dice[5],dice[3],dice[0],dice[4]]

while 1:
    n = I()
    if n == 0:
        break
    s = [[[0]*200 for i in range(200)] for j in range(100)]
    for i in range(n):
        t,f = LI()
        dice = make_dice(t,f)
        Set(s,dice)
    d = {0:0,1:0,2:0,3:0,4:0,5:0,6:0}
    for y in range(200):
        for x in range(200):
            for z in range(100):
                if s[z][y][x] == 0:
                    break
            d[s[z-1][y][x]] += 1

    for i in range(1,6):
        print(d[i],end = " ")
    print(d[6])

Submission status: Accepted

Solution code:
class Dice:

  def __init__(self, top=1, front=2, left=4, right=3, back=5, bottom=6):
    self.d = {"TOP": top, "FRONT": front, "LEFT": left, "RIGHT": right, "BACK": back, "BOTTOM": bottom}

  def roll_x(self):
    self._roll("TOP", "FRONT", "BOTTOM", "BACK")

  def roll_y(self):
    self._roll("FRONT", "LEFT", "BACK", "RIGHT")

  def roll_z(self):
    self._roll("TOP", "LEFT", "BOTTOM", "RIGHT")

  def _roll(self, a, b, c, d):
    self.d[a], self.d[b], self.d[c], self.d[d] = self.d[b], self.d[c], self.d[d], self.d[a]

  def all_rolls(self):
    import copy
    ret = []
    for i in range(6):
      if i % 2:
        self.roll_x()
      else:
        self.roll_y()
      for _ in range(4):
        self.roll_z()
        ret.append(copy.deepcopy(self))
    return ret

import copy
from collections import defaultdict
while True:
  n = int(input())
  if n==0:
    break

  board = [[0 for i in range(100)] for j in range(100)]
  height = [[0 for i in range(100)] for j in range(100)]

  for i in range(n):
    t, f = list(map(int, input().split()))
    dice = Dice()
    for di in dice.all_rolls():
      if di.d["TOP"]==t and di.d["FRONT"]==f:
        break

    x, y = 50, 50
    while True:
      dxy = []
      for s in ["FRONT", "LEFT", "BACK", "RIGHT"]:
        tt = di.d[s]
        if tt>=4:
          dxy.append((tt, s))
      dxy.sort(reverse=True)

      move = False
      for _, s in dxy:
        newdice = copy.deepcopy(di)
        if s=="FRONT":
          dx = 0
          dy = 1
          newdice.roll_x()
          newdice.roll_x()
          newdice.roll_x()
        elif s=="LEFT":
          dx = -1
          dy = 0
          newdice.roll_z()
          newdice.roll_z()
          newdice.roll_z()
        elif s=="BACK":
          dx = 0
          dy = -1
          newdice.roll_x()
        elif s=="RIGHT":
          dx = 1
          dy = 0
          newdice.roll_z()

        if height[x][y]>height[x+dx][y+dy]:
          x = x+dx
          y = y+dy
          di = newdice
          move = True
          break

      if not move:
        board[x][y] = di.d["TOP"]
        height[x][y] += 1
        break

  ans = defaultdict(int)
  for e in board:
    for ee in e:
      ans[ee] += 1
  print(*[ans[i] for i in range(1, 7)])

Submission status: Accepted

Solution code:
right_dic = {(1, 3):5, (1, 5):4, (1, 4):2, (1, 2):3,
             (2, 1):4, (2, 4):6, (2, 6):3, (2, 3):1,
             (3, 1):2, (3, 2):6, (3, 6):5, (3, 5):1,
             (4, 1):5, (4, 5):6, (4, 6):2, (4, 2):1,
             (5, 1):3, (5, 3):6, (5, 6):4, (5, 4):1,
             (6, 2):4, (6, 4):5, (6, 5):3, (6, 3):2}


class Dice:
    def __init__(self, top, front):
        self.top = top
        self.front = front
        self.right = right_dic[(top, front)]
        self.under = 7 - self.top
        self.back= 7 - self.front
        self.left = 7 - self.right

    def spin_right(self):
        self.top, self.right, self.under, self.left = self.left, self.top, self.right, self.under

    def spin_left(self):
        self.top, self.right, self.under, self.left = self.right, self.under, self.left, self.top

    def spin_front(self):
        self.top, self.front, self.under, self.back = self.back, self.top, self.front, self.under

    def spin_back(self):
        self.top, self.front, self.under, self.back = self.front, self.under, self.back, self.top


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

    mp = [[0] * (n * 2 + 2) for _ in range(n * 2 + 2)]
    show = [[0] * (n * 2 + 2) for _ in range(n * 2 + 2)]
    counter = [0] * 7
    STOP, FRONT, RIGHT, BACK, LEFT = 0, 1, 2, 3, 4
    for _ in range(n):
        x, y = n + 1, n + 1
        top, front = map(int, input().split())
        dice = Dice(top, front)
        while True:
            rec = 3
            direct = STOP
            if mp[y + 1][x] < mp[y][x] and dice.front > rec:
                rec = dice.front
                direct = FRONT
            if mp[y][x + 1] < mp[y][x] and dice.right > rec:
                rec = dice.right
                direct = RIGHT
            if mp[y - 1][x] < mp[y][x] and dice.back > rec:
                rec = dice.back
                direct = BACK
            if mp[y][x - 1] < mp[y][x] and dice.left > rec:
                rec = dice.left
                direct = LEFT

            if direct == STOP:
                mp[y][x] += 1
                counter[show[y][x]] -= 1
                counter[dice.top] += 1
                show[y][x] = dice.top
                break
            elif direct == FRONT:
                dice.spin_front()
                y += 1
            elif direct == RIGHT:
                dice.spin_right()
                x += 1
            elif direct == BACK:
                dice.spin_back()
                y -= 1
            elif direct == LEFT:
                dice.spin_left()
                x -= 1

    print(*counter[1:])