Problem:


Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

The input is given from Standard Input in the following format:

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

4 5 8
1 1
1 4
1 5
2 3
3 1
3 2
3 4
4 4

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

10 10 20
1 1
1 4
1 9
2 5
3 10
4 2
4 7
5 9
6 4
6 6
6 7
7 1
7 3
7 7
8 1
8 5
8 10
9 2
10 4
10 9

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0



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


Sample output:
0
0
0
2
4
0
0
0
0
0

Submission status: Accepted

Solution code:
from collections import defaultdict

def inside(x, y):    
    return 0 <= x <= h - 3 and 0 <= y <= w - 3

h, w, n = (int(_) for _ in input().split())
black = defaultdict(int)
for i in range(n):
    a, b = (int(_) - 1 for _ in input().split())
    for j in range(3):
        for k in range(3):
            x, y = a - j, b - k
            if not inside(x, y):
                continue
            black[(x, y)] += 1
ans = [0 for i in range(10)]
ans[0] = (h-2)*(w-2) - len(black)
for k in black:
    ans[black[k]] += 1
for i in range(10):
    print(ans[i])

Submission status: Accepted

Solution code:
def solve():
    w, h, n = [int(i) for i in input().split()]
    dic = dict()
    for i in range(n):
        a, b = map(lambda x: int(x) - 1, input().split())
        for j in range(3):
            for k in range(3):
                aj = a + j - 1
                bk = b + k - 1
                if 0 < aj and aj < w - 1 and 0 < bk and bk < h - 1:
                    if (aj, bk) in dic:
                        dic[(aj, bk)] += 1
                    else:
                        dic[(aj, bk)] = 1
    ans = [0 for i in range(10)]
    for v in dic.values():
        ans[v] += 1
    for i in range(10):
        if i == 0:
            print((w - 2) * (h - 2) - sum(ans))
        else:
            print(ans[i])


if __name__=="__main__":
    solve()

Submission status: Accepted

Solution code:
H, W, N = map(int, raw_input().split())
dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
dy = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
board = {}

for i in xrange(N):
    a, b = map(int, raw_input().split())
    for j in xrange(9):
        x, y = a+dx[j], b+dy[j]
        if x <= 1 or x >= H or y <= 1 or y >= W:
            continue
        if (x, y) in board:
            board[(x, y)] += 1
        else:
            board[(x, y)] = 1
ans = [0] * 10
for v in board.values():
    ans[v] += 1
ans[0] = (H-2)*(W-2)-sum(ans)
for a in ans:
    print a

Submission status: Accepted

Solution code:
from collections import Counter

h, w, n = [int(x) for x in input().split()]
cnt = Counter()

for _ in range(n):
    y, x = [int(x) for x in input().split()]
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if 2 <= x + dx < w and 2 <= y + dy < h:
                cnt[x + dx, y + dy] += 1

cnt2 = Counter(cnt.values())
print((h - 2) * (w - 2) - sum(cnt2.values()))
for c in range(1, 10):
    print(cnt2[c])

Submission status: Accepted

Solution code:
from collections import Counter
h, w, n = [int(i) for i in input().split()]

vs = []
for i in range(-1, 2):
	for j in range(-1, 2):
		vs.append((i,j))
cnt = []
for _ in range(n):
	a, b = [int(i) for i in input().split()]
	for v in vs:
		aa = a + v[0]
		bb = b + v[1]
		if 2<=aa<=(h-1) and 2<=bb<=(w-1):
			cnt.append(aa*w+bb)

cnt = Counter(cnt)


cnt2 = [0] * 10
cnt2[0] = (h-2)*(w-2)
for k in cnt:
	c = cnt[k]
	cnt2[c] += 1
	cnt2[0] -= 1

for i in cnt2:
	print(i)

Submission status: Runtime Error

Solution code:
h, w, n = map(int,input().split())
cell = [[0]*w for _ in range(h)]
for _ in range(n):
    a, b = map(int,input().split())
    for i in range(3):
        for j in range(3):
            if a-i>=0 and b-j>=0:
                cell[a-i-1][b-j-1] += 1
            else:
                continue

ans = [0]*10

for i in range(h-2):
    for j in range(w-2):
        s = cell[i][j]
        ans[s] += 1

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
h, w, n = map(int,input().split())
cell = [[0]*w for _ in range(h)]
for _ in range(n):
    a, b = map(int,input().split())
    cell[a-1][b-1] = 1

ans = [0]*10

for i in range(h-2):
    for j in range(w-2):
        s = [cell[i][j],cell[i+1][j],cell[i+2][j],cell[i][j+1],cell[i+1][j+1],cell[i+2][j+1],cell[i][j+2],cell[i+1][j+2],cell[i+2][j+2]].count(1)
        ans[s] += 1

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
H, W, N = map(int, input().split())
Grid = [[0]*(W-2) for _ in range(H-2)] #3*3正方形を左上のマスで区別。値は正方形内の黒塗りの個数
Ans = [(H-2)*(W-2) if i == 0 else 0 for i in range(10)] 
f = lambda x:int(x)-1
Draw = lambda x,y:[(x-i,y-j) for i in range(3) for j in range(3) if 0<=x-i<H-2 and 0<=y-j<W-2] #塗りつぶしたマスを含む正方形の座標のリストを返す関数
for _ in range(N):
    a, b = map(f, input().split())
    for x,y in Draw(a,b): #Ans及びGridの更新
        Ans[Grid[x][y]] += -1
        Ans[Grid[x][y]+1] += 1
        Grid[x][y] += 1
for ans in Ans:print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
h,w,n=map(int,input().split())
board=np.zeros((h,w))
for i in range(n):
    a,b=map(int,input().split())
    board[a-1][b-1]=1
result=[0]*10
for i in range(1,h-1):
    for j in range(1,w-1):
        tmp=0
        tmp=board[i][j]+board[i-1][j]+board[i+1][j]+board[i][j-1]+board[i+1][j-1]+board[i-1][j-1]+board[i][j+1]+board[i-1][j+1]+board[i+1][j+1]
        result[int(tmp)]+=1.0
for i in range(10):
    print(int(result[i]))

Submission status: Runtime Error

Solution code:
h,w,n=map(int,input().split())
D=dict()
for i in range(n):
    a,b=map(int,input().split())
    for p in range(-1,2):
        for q in range(-1,2):
            aa=a+p
            bb=b+q
            if 2<=aa<=h-1 and 2<=bb<=w-1:
                aabb=str(aa)+str(bb)
                if aabb in D:
                    D[aabb]+=1
                else:
                    D[aabb]=1
ans=[0]*10
V=list(D.values())
for v in V:
    ans[v]+=1
ans[0]=(h-2)*(w-2)-sum(ans)
for i in range(10):
    print(ans[i])

Submission status: Runtime Error

Solution code:
x, y, n = map(int, input().split())
box = [[0 for _ in range(y)] for _ in range(x)]
for _ in range(n):
    a, b = map(int, input().split())
    box[a - 1][b - 1] = 1
table = [0] * 9
for i in range(x - 2):
    for j in range(y - 2):
        total = sum(box[i][j:j + 3]) + sum(box[i + 1][j:j + 3]) + sum(box[i + 2][j:j + 3])
        table[total] += 1

[print(a) for a in table]

Submission status: Runtime Error

Solution code:
h, w, n = map(int, input().split())
from collections import defaultdict
d = defaultdict(int)
surround = [(0, 0), (1,1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)]
for _ in range(n):
    x, y  = map(int, input().split())
    x -= 1
    y -= 1
    for i in surround:
        if x + i[0] >= w or x + i[0] < 0 or y + i[1] < 0 or y + i[1] >= h:
            continue
        else:
            d[(x+i[0], y + i[1])] += 1
num = [0]*9
for key in d:
    if key[0] >= 1 and key[0] < h -1 and key[1] >= 1 and key[1] < w-1:
        num[d[key]] += 1
        
num[0] = (h-2)*(w-2) - sum(num)

for ans in num:
    print(ans)

Submission status: Runtime Error

Solution code:
h,w,n = input().split()
h,w,n = int(h), int(w), int(n)

import numpy as np
masu = np.zeros((h,w))

for i in range(n):
  x,y = input().split()
  x,y = int(x)-1, int(y)-1
  masu[x][y] = 1
  
count = [0] * 10

for i in range(h-2):
  for j in range(w-2):
    shiro = np.sum(masu[i:i+3,j:j+3])
    count[int(shiro)] += 1
print(*count, sep="\n")

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict

def input():
    return sys.stdin.readline().strip()

def recordnum(a,b):
    if not (0 < a < H-1 and 0 < b < W-1):
        return 
    else:
        res = M[(a,b)]
        for i,j in vector:
            res += M[(a+i,b+j)]
        num[res] += 1
        return


def dfs(a,b,color):

    if visited[(a,b)]:
        return
    
    recordnum(a,b)
    visited[(a,b)] = True

    if color == "b":
        for i,j in vector:
            x = a+i
            y = b+j
            if 0 < x < H-1 and 0 < y < W-1:
                if M[(x,y)]:
                    dfs(x,y,"b")
                else:
                    dfs(x,y,"w")
    else:
        ##白い箇所から白い箇所への探索はしない
        for i,j in vector:
            x = a+i
            y = b+j
            if 0 < x < H-1 and 0 < y < W-1 and M[(x,y)]:
                dfs(a,b,"b")

    


H,W,N = map(int,input().split())

M = defaultdict(int)
visited = defaultdict(int)
ab = []

for _ in range(N):
    a,b = map(int,input().split())
    ab.append([a-1,b-1])
    M[(a-1,b-1)] = 1


vector = [[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[1,-1],[-1,1]]
num = [0]*10

for a,b in ab:
    dfs(a,b,"b")

num[0] = (H-2)*(W-2) - sum(num)

for i in num:
    print(i)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    H,W,N=map(int,input().split())
    a,b=[0]*N,[0]*N
    for i in range(N):
        a[i],b[i]=map(int1,input().split())
    unique_a=list(set(a))
    unique_b=list(set(b))
    unique_a.sort()
    unique_b.sort()
    d_a,d_b={},{}
    tmp_a=0
    if unique_a:
        d_a[unique_a[0]]=tmp_a
        for i in range(len(unique_a)-1):
            tmp_a+=min(unique_a[i+1]-unique_a[i],3)
            d_a[unique_a[i+1]]=tmp_a
    tmp_b=0
    if unique_b:
        d_b[unique_b[0]]=tmp_b
        for i in range(len(unique_b)-1):
            tmp_b+=min(unique_b[i+1]-unique_b[i],3)
            d_b[unique_b[i+1]]=tmp_b
    c=[[0]*(tmp_b+1) for _ in range(tmp_a+1)]
    for i in range(N):
        c[d_a[a[i]]][d_b[b[i]]]+=1
    s=[[0]*(tmp_b+2) for _ in range(tmp_a+2)]
    for i in range(tmp_a+1):
        for j in range(tmp_b+1):
            s[i+1][j+1]=s[i][j+1]+s[i+1][j]-s[i][j]+c[i][j]
    ans=[0]*10
    for i in range(tmp_a-1):
        for j in range(tmp_b-1):
            ans[s[i+3][j+3]-s[i][j+3]-s[i+3][j]+s[i][j]]+=1
    ans[0]=(H-2)*(W-2)-sum(ans[1:])
    for row in ans:
        print(row)
    
    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)
from random import shuffle

def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    class TwoDimNode:
        def __init__(self, x=None, y=None, parent=None, left=None, right=None):
            """
            2 次元二分探索木のためのノード
            """        
            self.x = x
            self.y = y
            self.parent = parent
            self.left = left
            self.right = right
            self.flag = True

    class TwoDimTree:
        def __init__(self, points=[]):
            """
            2 次元二分探索木 (kD tree) を作成する
            root の深さを 0 として、深さが偶数の場合そこでは x を基準に、奇数の場合 y を基準に二分探索木条件を満たすようにする
            """
            # nil の設定
            self.nil = TwoDimNode()
            self.nil.parent = self.nil
            self.nil.left = self.nil
            self.nil.right = self.nil
            # root の設定
            self.root = self.nil
            # もし予め一次元の点の集合が与えられるのならバランスする形で kD tree を構築する
            self._balance_insert(points)
        
        def preorder_traverse(self, node=None):
            node = self.root if node is None else node
            if node != self.nil:
                print(f"({node.x},{node.y})", end=' ')
                self.preorder_traverse(node=node.left)
                self.preorder_traverse(node=node.right)
            
        def postorder_traverse(self, node=None):
            node = self.root if node is None else node
            if node != self.nil:
                self.preorder_traverse(node=node.left)
                self.preorder_traverse(node=node.right)
                print(f"({node.x},{node.y})", end=' ')

        def inorder_traverse(self, node=None):
            node = self.root if node is None else node
            if node != self.nil:
                self.preorder_traverse(node=node.left)
                print(f"({node.x},{node.y})", end=' ')
                self.preorder_traverse(node=node.right)
        
        def _balance_insert(self, seq, depth=0):
            # 毎回 x or y をキーとしてソートを行い、中央値をとって insert すれば平衡になる
            if seq:
                arranged = sorted(seq, key=itemgetter(depth % 2))
                mid = len(seq) // 2
                self.insert(seq[mid][0], seq[mid][1])
                self._balance_insert(arranged[:mid], depth+1)
                self._balance_insert(arranged[mid+1:], depth+1)


        def insert(self, x, y):
            """
            kD tree に値が (x, y) であるノードを O(depth) で挿入する
            (コンストラクタで生成した kD tree は平衡であることが保証されるが、insert により生成した部分の平衡性は保証されないことに注意)        
            """
            trailer = self.nil    # (x, y) を挿入するべき nil の一つ前のノードを保存するトレーラポインタ
            pos = self.root    # (x, y) を挿入するべき nil の場所を探す
            depth = 0
            while pos != self.nil:
                trailer = pos
                k, pos_k = (x, pos.x) if depth % 2 == 0 else (y, pos.y)
                if k < pos_k:
                    pos = pos.left
                elif pos_k < k:
                    pos = pos.right
                else:
                    pos.flag ^= pos.flag
                    pos = pos.left if pos.flag else pos.right
                depth += 1
            inserted_node = TwoDimNode(x, y, trailer, self.nil, self.nil)
            # trailer の depth
            depth -= 1
            k, trailer_k = (x, trailer.x) if depth % 2 == 0 else (y, trailer.y)
            # tree is empty
            if trailer == self.nil:
                self.root = inserted_node
            # どこかのノードの子供の位置に挿入する時
            elif k < trailer_k or (k == trailer_k and trailer.flag):
                trailer.left = inserted_node
            else:
                trailer.right = inserted_node
        
        def two_dim_search(self, sx, tx, sy, ty, node=None, depth=0):
            """
            kD tree に対し閉区間 D = {(x, y) | sx<=x<=tx, sy<=y<=ty} 内に存在する点を探してリストにまとめて返す (対応する点の個数 k として O(√n + k))
            下記のように検索必要性を判断し再帰的に左右の子に対し探索を行えば良い

            <-------- node.x -------->
            <----------->
            少しでも [sx,tx] が左側ゾーン ((-inf, node.x]) に被っていたら検索しておく必要がある
                        <----->
                        少しでも [sx, tx] が右側ゾーン ([node.x, inf)) に被っていたら検索しておく必要がある
            """        
            cnt = 0
            node = self.root if node is None else node
            # print(f"{node.x} {node.y}")
            if depth % 2 == 0:
                if node.left != self.nil and sx <= node.x:
                    cnt += self.two_dim_search(sx, tx, sy, ty, node.left, depth+1)
                if sx <= node.x <= tx and sy <= node.y <= ty:
                    cnt += 1
                if node.right != self.nil and tx >= node.x:
                    cnt += self.two_dim_search(sx, tx, sy, ty, node.right, depth+1)
            else:
                if node.left != self.nil and sy <= node.y:
                    cnt += self.two_dim_search(sx, tx, sy, ty, node.left, depth+1)
                if sx <= node.x <= tx and sy <= node.y <= ty:
                    cnt += 1
                if node.right != self.nil and ty >= node.y:
                    cnt += self.two_dim_search(sx, tx, sy, ty, node.right, depth+1)
            return cnt


    def unvisited_p(d, i, j):
        if i in d:
            if j in d[i]:
                return False
        return True

    def register(d, i, j):
        if i not in d:
            d[i] = set()
            d[i].add(j)
        else:
            d[i].add(j)

    
    h, w, n = mi()
    points = [lmi() for _ in range(n)]
    shuffle(points)

    num_of_grids_contains_black = [0] * 10

    # kD tree 処理
    kd_tree = TwoDimTree()
    for x, y in points:
        kd_tree.insert(x, y)

    d = dict()
    for x, y in points:
        # print(f"{x} {y} {kd_tree.two_dim_search(x-1, x+1, y-1, y+1)}")
        for i in range(x-1, x+2):
            for j in range(y-1, y+2):
                if 2 <= i <= h-1 and 2 <= j <= w-1 and unvisited_p(d, i, j):    # 探索する 3*3 grid のセンター
                    num_of_grids_contains_black[kd_tree.two_dim_search(i-1, i+1, j-1, j+1)] += 1
                    register(d, i, j)


    num_of_grids_contains_black[0] = (h - 2) * (w - 2) - sum(num_of_grids_contains_black[1:])
    print(*num_of_grids_contains_black, sep='\n')



if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)
from random import shuffle

def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    class TwoDimNode:
        def __init__(self, x=None, y=None, parent=None, left=None, right=None):
            self.x = x
            self.y = y
            self.parent = parent
            self.left = left
            self.right = right
            self.flag = True

    class TwoDimTree:
        def __init__(self):
            self.nil = TwoDimNode()
            self.nil.parent = self.nil
            self.nil.left = self.nil
            self.nil.right = self.nil
            self.root = self.nil
        
        def preorder_traverse(self, node=None):
            if node is None:
                node = self.root
            if node != self.nil:
                print(f"({node.x},{node.y})", end=' ')
                self.preorder_traverse(node=node.left)
                self.preorder_traverse(node=node.right)

        def post_order_traverse(self, node=None):
            if node is None:
                node = self.root
            if node != self.nil:
                self.post_order_traverse(node=node.left)
                self.post_order_traverse(node=node.right)
                print(f"({node.x},{node.y})", end=' ')
                
        def insert(self, x, y):
            trailer = self.nil
            pos = self.root
            depth = 0
            while pos != self.nil:
                trailer = pos
                if depth % 2 == 0:
                    k, pos_k = x, pos.x
                else:
                    k, pos_k = y, pos.y
                if k < pos_k:
                    pos = pos.left
                elif pos_k < k:
                    pos = pos.right
                else:
                    pos.flag ^= pos.flag
                    pos = pos.left if pos.flag else pos.right
                depth += 1
            inserted_node = TwoDimNode(x, y, trailer, self.nil, self.nil)
            # trailer の depth
            depth -= 1
            if depth % 2 == 0:
                k, trailer_k = x, trailer.x
            else:
                k, trailer_k = y, trailer.y
            # tree is empty
            if trailer == self.nil:
                self.root = inserted_node
            elif k < trailer_k or (k == trailer_k and trailer.flag):
                trailer.left = inserted_node
            else:
                trailer.right = inserted_node
        
        def two_dim_search(self, sx, tx, sy, ty, node=None, depth=0):
            buf = []
            if node is None:
                node = self.root
            # print(f"{node.x} {node.y}")
            if depth % 2 == 0:
                if node.left != self.nil and sx <= node.x:
                    buf += self.two_dim_search(sx, tx, sy, ty, node.left, depth+1)
                if sx <= node.x <= tx and sy <= node.y <= ty:
                    buf.append((node.x, node.y))
                if node.right != self.nil and tx >= node.x:
                    buf += self.two_dim_search(sx, tx, sy, ty, node.right, depth+1)
            else:
                if node.left != self.nil and sy <= node.y:
                    buf += self.two_dim_search(sx, tx, sy, ty, node.left, depth+1)
                if sx <= node.x <= tx and sy <= node.y <= ty:
                    buf.append((node.x, node.y))
                if node.right != self.nil and ty >= node.y:
                    buf += self.two_dim_search(sx, tx, sy, ty, node.right, depth+1)
            return buf

    def unvisited_p(d, i, j):
        if i in d:
            if j in d[i]:
                return False
        return True

    def register(d, i, j):
        if i not in d:
            d[i] = set()
            d[i].add(j)
        else:
            d[i].add(j)

    
    h, w, n = mi()
    points = [lmi() for _ in range(n)]
    shuffle(points)

    num_of_grids_contains_black = [0] * 10

    # kD tree 処理
    kd_tree = TwoDimTree()
    for x, y in points:
        kd_tree.insert(x, y)
    
    # kd_tree.preorder_traverse()
    # print('')
    # kd_tree.post_order_traverse()
    # print('')



    d = dict()
    for x, y in points:
        # print(f"{x} {y} {kd_tree.two_dim_search(x-1, x+1, y-1, y+1)}")
        for i in range(x-1, x+2):
            for j in range(y-1, y+2):
                if 2 <= i <= h-1 and 2 <= j <= w-1 and unvisited_p(d, i, j):    # 探索する 3*3 grid のセンター
                    # print(f"{i} {j}")
                    # print(kd_tree.two_dim_search(i-1, i+1, j-1, j+1))
                    num_of_grids_contains_black[len(kd_tree.two_dim_search(i-1, i+1, j-1, j+1))] += 1
                    register(d, i, j)


    num_of_grids_contains_black[0] = (h - 2) * (w - 2) - sum(num_of_grids_contains_black[1:])
    print(*num_of_grids_contains_black, sep='\n')



if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
H, W , N = map(int,input().split())
from bisect import bisect_left
from bisect import bisect_right
matrix = []
for _ in range(N):
    x,y = map(int,input().split())
    matrix.append([x-1,y-1])
ans = [0 for _ in range(10)]
cand = {}
for l in matrix:
    for x_r in [-2, -1 , 0]:
        for y_r in [-2, -1 , 0]:
            nowx = l[0] + x_r
            nowy = l[1] + y_r
            if nowx < 0 or nowy < 0 or nowx + 2>= H or nowy+ 2 >= W:
                continue
            #ここで起点(左上)nowx, nowy として　 9マスに着目する
            name = str(nowx) + ' '  +str(nowy)
            if name in cand : cand[name] += 1
            else: cand[name] = 1
tmp = ((H - 2) * (W - 2))
[ans[x]+=1 for x in cand.values()]
ans[0] -= len(cand)
for x in ans:
    print(x)

Submission status: Runtime Error

Solution code:
H, W , N = map(int,input().split())
from bisect import bisect_left
from bisect import bisect_right
matrix = []
for _ in range(N):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    matrix.append([x,y])
matrix.sort()
ans = [0 for _ in range(10)]
cand = {}
for l in matrix:
    for x_r in [-2, -1 , 0]:
        for y_r in [-2, -1 , 0]:
            nowx = l[0] + x_r
            nowy = l[1] + y_r
            if nowx < 0 or nowy < 0 or nowx + 2>= H or nowy+ 2 >= W:
                continue
            #ここで起点(左上)nowx, nowy として　 9マスに着目する
            name = str(nowx) + ' '  +str(nowy)
            if not name in cand : cand[name] += 1
            else: cand[name] = 1
tmp = ((H - 2) * (W - 2))
for x in cand.values():
    ans[x] += 1
    tmp -= 1
ans[0] = tmp
for x in ans:
    print(x)

Submission status: Runtime Error

Solution code:
H, W , N = map(int,input().split())
from bisect import bisect_left
from bisect import bisect_right
matrix = []
for _ in range(N):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    matrix.append([x,y])
matrix.sort()
ans = [0 for _ in range(10)]
cand = {}
for l in matrix:
    for x_r in [-2, -1 , 0]:
        for y_r in [-2, -1 , 0]:
            nowx = l[0] + x_r
            nowy = l[1] + y_r
            if nowx < 0 or nowy < 0 or nowx + 2>= H or nowy+ 2 >= W:
                continue
            #ここで起点(左上)nowx, nowy として　 9マスに着目する
            name = str(nowx)  +str(nowy)
            try: cand[name] += 1
            except: cand[name] = 1
tmp = ((H - 2) * (W - 2))
for x in cand.values():
    ans[x] += 1
    tmp -= 1
ans[0] = tmp
for x in ans:
    print(x)

Submission status: Runtime Error

Solution code:
H, W , N = map(int,input().split())
from bisect import bisect_left
from bisect import bisect_right
matrix = []
for _ in range(N):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    matrix.append([x,y])
matrix.sort()
ans = [0 for _ in range(10)]
cand = {}
for l in matrix:
    for x_r in [-2, -1 , 0]:
        for y_r in [-2, -1 , 0]:
            nowx = l[0] + x_r
            nowy = l[1] + y_r
            if nowx < 0 or nowy < 0 or nowx + 2>= H or nowy+ 2 >= W:
                continue
            #ここで起点(左上)nowx, nowy として　 9マスに着目する
            name = str(nowx) + str(nowy)
            try: cand[name] += 1
            except: cand[name] = 1
tmp = ((H - 2) * (W - 2))
for x in cand.values():
    if x == 9:
        while True:
            print(W)
    ans[x] += 1
    tmp -= 1
ans[0] = tmp
for x in ans:
    print(x)