Problem:


平面に長方形のシートが何枚か置かれている. これらのシートで覆われている部分の面積や周長を求めるプログラムを作成せよ.

ただし, 平面を座標平面とみなしたとき, シートの配置は次の条件 (1), (2) を満たすものとする.

(1) 各シートの長方形の 4 頂点の x, y 座標は全て 0 以上 10000 以下の整数であり, 長方形の各辺は x 軸, または y 軸に平行である.

(2) シートの枚数は高々 10000 枚以下である.

n と問題の種類を表す整数 r が空白で区切って書かれている. 2 行目以降の各行には, 各シートの左下頂点座標 (x1, y1) と右上頂点座標 (x2, y2) の座標値が x1, y1, x2, y2 の順で空白で区切って書いてある.

出力ファイルのファイル名は “output.txt” である.“output.txt” には r = 1 のとき 1 行目に面積を, r = 2 のとき 1 行目に面積, 2 行目に周囲の長さを出力する. いずれの場合も最後に改行を入れること.

-->

入力データ の 1 行目に長方形の個数 n と問題の種類を表す整数 r が空白で区切って書かれている. 2 行目以降の各行には, 各シートの左下頂点座標 (x1, y1) と右上頂点座標 (x2, y2) の座標値が x1, y1, x2, y2 の順で空白で区切って書いてある.

出力には r = 1 のとき 1 行目に面積を, r = 2 のとき 1 行目に面積, 2 行目に周囲の長さを出力する. いずれの場合も最後に改行を入れること.

   また, テストデータの 40% では長方形の頂点の座標が 0 以上 100 以下で, そのうちの 1/2 では面積だけを求める問題である. さらに, 全体の 1/2 は面積だけを求める問題である.

 

  入力例１
  入力例２
  入力例３
  入力例４

 

5 1   5 2   2 2   3 2   

0 0 3 2   0 0 3 2   0 0 8 9   2 2 8 8   

1 1 2 5   1 1 2 5   0 0 9 8   3 0 4 9   

0 4 6 5   0 4 6 5      5 0 7 9   

3 3 5 6   3 3 5 6         

5 0 7 6   5 0 7 6         

  　

  出力例１
  出力例２
  出力例３
  出力例４

29  29  80   45  

  38  36   36  

入力

入力は複数のデータセットからなる．n, r がともに 0 のとき入力が終了する．データセットの数は 10 を超えない．

出力

データセットごとに, r = 1 のとき 1 行目に面積を, r = 2 のとき 1 行目に面積, 2 行目に周囲の長さを出力する.

入力例

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

出力例

29
29
38
80
36
45
36

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。



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


Sample output:
29
29
38
80
36
45
36

Submission status: Wrong Answer

Solution code:
a=3

Submission status: Wrong Answer

Solution code:
print '3'

Submission status: Wrong Answer

Solution code:
import csv

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))

    table_c = [0] * 10001
    table_r = [0] * 10001
    table_e = [0] * 10001

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if not rx or rx < x1:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e[y] += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 1:
        continue

    around = 0
    prev_w = 0
    for y, w in enumerate(table_c):
        around += abs(w - prev_w) + (table_e[y] if w else 0)
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))
    table = [[0, 0, 0] for _ in range(10001)]

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            t = table[y]
            rx = t[1]
            if not rx or rx < x1:
                t[0] += x2 - x1
                t[1] = x2
                t[2] += 2
            elif rx < x2:
                t[0] += x2 - rx
                t[1] = x2

    print(sum(t[0] for t in table))
    if r == 1:
        continue

    around = 0
    prev_w = 0
    for y, (w, rx, e) in enumerate(table):
        around += abs(w - prev_w) + (e if w else 0)
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))

    table_c = [0] * 10001
    table_r = [0] * 10001
    table_e = [0] * 10001

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if rx < x1 or not rx:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e[y] += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 1:
        continue

    around = 0
    prev_w = 0
    for y, w in enumerate(table_c):
        around += abs(w - prev_w) + (table_e[y] if w else 0)
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))

    table_c = [0] * 10001
    table_r = [0] * 10001
    table_e = 0

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if rx < x1 or not rx:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 1:
        continue

    around = 0
    prev_w = 0
    for w in table_c:
        around += abs(w - prev_w) + table_e
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))

    table_c = [0] * 10000
    table_r = [0] * 10000
    table_e = 0

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if rx < x1 or not rx:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 1:
        continue

    around = 0
    prev_w = 0
    for w in table_c:
        around += abs(w - prev_w) + table_e
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))
    max_y = max(p[3] for p in sheets)

    table_c = [0] * max_y
    table_r = [0] * max_y
    table_e = 0

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if rx < x1 or not rx:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 1:
        continue

    around = table_e
    prev_w = 0
    for w in table_c:
        around += abs(w - prev_w)
        prev_w = w
    around += prev_w

    print(around)

Submission status: Time Limit Exceeded

Solution code:
from operator import sub

while True:
    n, r = map(int, input().split())
    if not n:
        break

    sheets = sorted(tuple(map(int, input().split())) for _ in range(n))
    max_y = max(p[3] for p in sheets)

    table_c = [0] * (max_y + 1)
    table_r = [0] * max_y
    table_e = 0

    for x1, y1, x2, y2 in sheets:
        for y in range(y1, y2):
            rx = table_r[y]
            if rx < x1 or not rx:
                table_c[y] += x2 - x1
                table_r[y] = x2
                table_e += 2
            elif rx < x2:
                table_c[y] += x2 - rx
                table_r[y] = x2

    print(sum(table_c))
    if r == 2:
        print(sum(map(abs, map(sub, table_c, [0] + table_c))) + table_e)

Submission status: Time Limit Exceeded

Solution code:
import csv

while 1:
	line=raw_input()
	n, r = map(int, line.split(' '))
	
	if n == 0 and r == 0:
		break

	data = []
	for i in xrange(n):
		line = raw_input()
		data.append(map(int, line.split(' ')))
	
	X = max(map(lambda x:x[2],data))
	Y = max(map(lambda x:x[3],data))
	
	area = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
	
	if r == 2:
		area1 = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
		area2 = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
	
	for d in data:
		for y in xrange(d[1]+1, d[3]+1):
			for x in xrange(d[0]+1,d[2]+1):
				area[y][x] = 1
				if r == 2:
					area1[y][x+1] = 1
					area2[y+1][x] = 1
				
	menseki = 0
	for line in area:
		menseki += sum(line)
	print '{}'.format(menseki)
	
	if r == 2:
		nagasa = 0
		for a, (a1, a2) in zip(area, zip(area1, area2)):
			nagasa += sum([abs(b-b1)+abs(b-b2) for b, (b1, b2) in zip(a, zip(a1,a2))])
		print '{}'.format(nagasa)
	"""
	area2 = np.zeros([X+2,Y+2])
	area2[1:-1,1:-1] = area

	if r == 2:
		tate = len(np.nonzero(area2[:-1,:] - area2[1:,:])[0])
		tate += len(np.nonzero(area2[:,:-1] - area2[:,1:])[0])
		print '{}'.format(tate)
	"""

Submission status: Time Limit Exceeded

Solution code:
from itertools import chain


max_size = 10002
while 1:
  n, r = (int(i) for i in input().strip().split())
  if n == r == 0:
    break
  flag = False if r == 2 else True
  sheets = dict()
  max_size = 0

  for i in range(n):
    points = tuple(int(i) + 1 for i in input().strip().split())
    max_size = max(max_size, max(points))
    sheets[points[0]] = tuple(chain(sheets.get(points[0], ()), ((points[1], 1), (points[3], -1))))
    sheets[points[2]] = tuple(chain(sheets.get(points[2], ()), ((points[3], 1),( points[1], -1))))
  max_size += 2

  size, perimeter = 0, 0
  # dp[0] is left, dp[1] is now vertical line
  dp = [dict(), dict()]

  for x in range(0, max_size):
    dp[1] = dict()

    # put value to each point
    for i in range(0, len(sheets.get(x, ()))):
      pos, val = sheets[x][i]
      dp[1][pos] = val + dp[1].get(pos, 0)

    # paint '1' to left line, and '-1' to right line
    for y in range(1, max_size):
      dp[1][y] = dp[1].get(y, 0) + dp[1].get(y - 1, 0)

    # merge `left' and `now'
    for y in range(1, max_size):
      dp[1][y] = dp[1].get(y, 0) + dp[0].get(y, 0)

    # check and add 
    for y in range(1, max_size):
      # if `now' or `left' equal zero, and another more than zero.
      up = (dp[0].get(y, 0) == 0 and dp[1].get(y, 0) > 0) \
          or (dp[0].get(y, 0) > 0 and dp[1].get(y, 0) == 0)
      # if `now' or `under' equal zero, and another more than zero.
      left = (dp[1].get(y - 1, 0) == 0 and dp[1].get(y, 0) > 0) \
          or (dp[1].get(y - 1, 0) > 0 and dp[1].get(y, 0) == 0)
      # if `now' is more than zero.
      flag = dp[1].get(y, 0) > 0

      perimeter += up + left
      size += flag

    dp = [dp[1], dp[0]]

  print(size)
  if r == 2:
    print(perimeter)

Submission status: Time Limit Exceeded

Solution code:
from itertools import chain


max_size = 10002
while 1:
  n, r = (int(i) for i in input().strip().split())
  if n == r == 0:
    break
  flag = False if r == 2 else True
  sheets = dict()
  max_size = 0

  for i in range(n):
    points = tuple(int(i) + 1 for i in input().strip().split())
    max_size = max(max_size, max(points))
    sheets[points[0]] = tuple(chain(sheets.get(points[0], ()), ((points[1], 1), (points[3], -1))))
    sheets[points[2]] = tuple(chain(sheets.get(points[2], ()), ((points[3], 1),( points[1], -1))))
  max_size += 2

  size, perimeter = 0, 0
  # dp[0] is left, dp[1] is now vertical line
  dp0, dp1 = dict(), dict()

  for x in range(0, max_size):

    # put value to each point
    for i in range(0, len(sheets.get(x, ()))):
      pos, val = sheets[x][i]
      dp1[pos] = val + dp1.get(pos, 0)

    # paint '1' to left line, and '-1' to right line
    for y in range(1, max_size):
      dp1[y] = dp1.get(y, 0) + dp1.get(y - 1, 0)

    # merge `left' and `now'
    for y in range(1, max_size):
      dp1[y] = dp1.get(y, 0) + dp0.get(y, 0)

    # check and add 
    for y in range(1, max_size):
      # if `now' or `left' equal zero, and another more than zero.
      up = (dp0.get(y, 0) == 0 and dp1.get(y, 0) > 0) \
          or (dp0.get(y, 0) > 0 and dp1.get(y, 0) == 0)
      # if `now' or `under' equal zero, and another more than zero.
      left = (dp1.get(y - 1, 0) == 0 and dp1.get(y, 0) > 0) \
          or (dp1.get(y - 1, 0) > 0 and dp1.get(y, 0) == 0)
      # if `now' is more than zero.
      flag = dp1.get(y, 0) > 0

      perimeter += up + left
      size += flag

    dp0, dp1 = dp1, dict()

  print(size)
  if r == 2:
    print(perimeter)

Submission status: Runtime Error

Solution code:
def main():
  while True:
    n, r = map(int, input().split())
    if n == 0:
      break
    plst = []
    minx = miny = 20000
    maxx = maxy = 0
    for _ in range(n):
      x1, y1, x2, y2 = map(int, input().split())
      minx = min(minx, x1)
      miny = min(miny, y1)
      maxx = max(maxx, x2)
      maxy = max(maxy, y2)
      plst.append((x1, y1, x2, y2))
    mp = [[0] * (maxx + 5) for _ in range(maxy + 5)]
    for x1, y1, x2, y2 in plst:
      mp[y1 + 1][x1 + 1] += 1
      mp[y1 + 1][x2 + 1] -= 1
      mp[y2 + 1][x1 + 1] -= 1
      mp[y2 + 1][x2 + 1] += 1
  
    for line in mp:
      acc = 0
      for x in range(maxx + 5):
        acc += line[x]
        line[x] = acc
    for x in range(maxx + 5):
      acc = 0
      for y in range(maxy + 5):
        acc += mp[y][x]
        mp[y][x] = bool(acc)
    
    if r == 1:
      ans = 0
      for line in mp:
        ans += sum(line)
      print(ans)
    else:
      ans1 = ans2 = 0
      for y in range(1, maxy + 4):
        for x in range(1, maxx + 4):
          if mp[y][x]:
            ans1 += 1
            ans2 += (4 - mp[y + 1][x] - mp[y - 1][x] - mp[y][x + 1] - mp[y][x - 1])
      print(ans1, ans2,sep="\n")

main()

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

area = np.zeros([10002,10002])

fw = open('output.txt', 'w')

with open('input.txt') as f:
	data = [line for line in csv.reader(f, delimiter=' ')]
n, r = data[0]
for i in range(1, n+1):
	area[data[i][0]:data[i][2]+1,data[i][1]:data[i][3]+1] = 1
	
menseki = len(np.nonzero(area)[0])
fw.write('{}\n'.format(menseki))

if r == 2:
	tate = len(np.nonzero(area[:-1,:] - area[1:,:])[0])
	tate += len(np.nonzero(area[:,:-1] - area[:,1:])[0])
	fw.write('{}\n'.format(tate))

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

area = np.zeros([10002,10002])

while (line=raw_input()):
	n, r = map(int, line.split(' '))

	for i in xrange(n):
		line = raw_input()
		data = map(int, line.split(' '))
		area[data[0]:data[2]+1,data[1]:data[3]+1] = 1
		
	menseki = len(np.nonzero(area)[0])
	print '{}\n'.format(menseki)

	if r == 2:
		tate = len(np.nonzero(area[:-1,:] - area[1:,:])[0])
		tate += len(np.nonzero(area[:,:-1] - area[:,1:])[0])
		print '{}\n'.format(tate)

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

while 1:
	line=raw_input()
	n, r = map(int, line.split(' '))
	
	if n == 0:
		break

	data = []
	for i in xrange(n):
		line = raw_input()
		data.append(map(int, line.split(' ')))
	
	data = np.array(data)
	X = np.max(data[:,2])
	Y = np.max(data[:,3])
	
	area = np.zeros([X,Y])
	
	for d in data:
		area[d[0]:d[2],d[1]:d[3]] = 1
		
	menseki = len(np.nonzero(area)[0])
	print '{}\n'.format(menseki)
	
	area2 = np.zeros([X+2,Y+2])
	area2[1:-1,1:-1] = area

	if r == 2:
		tate = len(np.nonzero(area2[:-1,:] - area2[1:,:])[0])
		tate += len(np.nonzero(area2[:,:-1] - area2[:,1:])[0])
		print '{}\n'.format(tate)

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

while 1:
    line=raw_input()
    n, r = map(int, line.split(' '))
    
    if n == 0:
        break

    data = []
    for i in xrange(n):
        line = raw_input()
        data.append(map(int, line.split(' ')))
    
    data = np.array(data)
    X = np.max(data[:,2])
    Y = np.max(data[:,3])
    
    area = np.zeros([X,Y])
    
    for d in data:
        area[d[0]:d[2],d[1]:d[3]] = 1
        
    menseki = len(np.nonzero(area)[0])
    print '{}\n'.format(menseki)
    
    area2 = np.zeros([X+2,Y+2])
    area2[1:-1,1:-1] = area

    if r == 2:
        tate = len(np.nonzero(area2[:-1,:] - area2[1:,:])[0])
        tate += len(np.nonzero(area2[:,:-1] - area2[:,1:])[0])
        print '{}\n'.format(tate)

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

while 1:
    line=raw_input()
    n, r = map(int, line.split(' '))
    
    if n == 0:
        break

    data = []
    for i in xrange(n):
        line = raw_input()
        data.append(map(int, line.split(' ')))
    
    data = np.array(data)
    X = np.max(data[:,2])
    Y = np.max(data[:,3])
    
    area = np.zeros([X,Y])
    
    for d in data:
        area[d[0]:d[2],d[1]:d[3]] = 1
        
    menseki = len(np.nonzero(area)[0])
    print '{}'.format(menseki)
    
    area2 = np.zeros([X+2,Y+2])
    area2[1:-1,1:-1] = area

    if r == 2:
        tate = len(np.nonzero(area2[:-1,:] - area2[1:,:])[0])
        tate += len(np.nonzero(area2[:,:-1] - area2[:,1:])[0])
        print '{}'.format(tate)

Submission status: Runtime Error

Solution code:
import numpy as np
import csv

while 1:
    line=raw_input()
    n, r = map(int, line.split(' '))
    
    if n == 0 and r == 0:
        break

    data = []
    for i in xrange(n):
        line = raw_input()
        data.append(map(int, line.split(' ')))
    
    data = np.array(data)
    X = np.max(data[:,2])
    Y = np.max(data[:,3])
    
    area = np.zeros([X,Y])
    
    for d in data:
        area[d[0]:d[2],d[1]:d[3]] = 1
        
    menseki = len(np.nonzero(area)[0])
    print '{}'.format(menseki)
    
    area2 = np.zeros([X+2,Y+2])
    area2[1:-1,1:-1] = area

    if r == 2:
        tate = len(np.nonzero(area2[:-1,:] - area2[1:,:])[0])
        tate += len(np.nonzero(area2[:,:-1] - area2[:,1:])[0])
        print '{}'.format(tate)

Submission status: Runtime Error

Solution code:
import numpy as np

Submission status: Runtime Error

Solution code:
import numpy
import csv

while 1:
	line=raw_input()
	n, r = map(int, line.split(' '))
	
	if n == 0 and r == 0:
		break

	data = []
	for i in xrange(n):
		line = raw_input()
		data.append(map(int, line.split(' ')))
	
	X = max(map(lambda x:x[2],data))
	Y = max(map(lambda x:x[3],data))
	
	area = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
	
	if r == 2:
		area1 = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
		area2 = [[0 for x in xrange(X+2)] for y in xrange(Y+2)]
	
	for d in data:
		for y in xrange(d[1]+1, d[3]+1):
			for x in xrange(d[0]+1,d[2]+1):
				area[y][x] = 1
				if r == 2:
					area1[y][x+1] = 1
					area2[y+1][x] = 1
				
	menseki = 0
	for line in area:
		menseki += sum(line)
	print '{}'.format(menseki)
	
	if r == 2:
		nagasa = 0
		for a, (a1, a2) in zip(area, zip(area1, area2)):
			nagasa += sum([abs(b-b1)+abs(b-b2) for b, (b1, b2) in zip(a, zip(a1,a2))])
		print '{}'.format(nagasa)

Submission status: Runtime Error

Solution code:
from numpy import *

Submission status: Runtime Error

Solution code:


from itertools import chain

with 0 as efafe:
  max_size = 10002
  while 1:
    n, r = (int(i) for i in input().strip().split())
    if n == r == 0:
      break
    flag = False if r == 2 else True
    sheets = dict()
    max_size = 0

    for i in range(n):
      points = tuple(int(i) + 1 for i in input().strip().split())
      max_size = max(max_size, max(points))
      sheets[points[0]] = tuple(chain(sheets.get(points[0], ()), ((points[1], 1), (points[3], -1))))
      sheets[points[2]] = tuple(chain(sheets.get(points[2], ()), ((points[3], 1),( points[1], -1))))
    max_size += 2

    size, perimeter = 0, 0
    # dp[0] is left, dp[1] is now vertical line
    dp0, dp1 = dict(), dict()

    for x in range(0, max_size):

      # put value to each point
      for i in range(0, len(sheets.get(x, ()))):
        pos, val = sheets[x][i]
        dp1[pos] = val + dp1.get(pos, 0)

      # paint '1' to left line, and '-1' to right line
      for y in range(1, max_size):
        dp1[y] = dp1.get(y, 0) + dp1.get(y - 1, 0)

      # merge `left' and `now'
      for y in range(1, max_size):
        dp1[y] = dp1.get(y, 0) + dp0.get(y, 0)

      # check and add 
      for y in range(1, max_size):
        # if `now' or `left' equal zero, and another more than zero.
        up = (dp0.get(y, 0) == 0 and dp1.get(y, 0) > 0) \
            or (dp0.get(y, 0) > 0 and dp1.get(y, 0) == 0)
        # if `now' or `under' equal zero, and another more than zero.
        left = (dp1.get(y - 1, 0) == 0 and dp1.get(y, 0) > 0) \
            or (dp1.get(y - 1, 0) > 0 and dp1.get(y, 0) == 0)
        # if `now' is more than zero.
        flag = dp1.get(y, 0) > 0

        perimeter += up + left
        size += flag

      dp0, dp1 = dp1, dict()

    print(size)
    if r == 2:
      print(perimeter)

Submission status: Runtime Error

Solution code:
max_size = 10002
while 1:
  n, r = (int(i) for i in input().strip().split())
  if n == r == 0:
    break
  flag = False if r == 2 else True
  sheets = dict()
  max_size = 0

  for i in range(n):
    points = tuple(int(i) + 1 for i in input().strip().split())
    max_size = max(max_size, max(points))
    sheets[points[0]] = tuple(chain(sheets.get(points[0], ()), ((points[1], 1), (points[3], -1))))
    sheets[points[2]] = tuple(chain(sheets.get(points[2], ()), ((points[3], 1),( points[1], -1))))
  max_size += 2

  size, perimeter = 0, 0
  # dp[0] is left, dp[1] is now vertical line
  dp0, dp1 = dict(), dict()

  for x in range(0, max_size):

    # put value to each point
    for i in range(0, len(sheets.get(x, ()))):
      pos, val = sheets[x][i]
      dp1[pos] = val + dp1.get(pos, 0)

    # paint '1' to left line, and '-1' to right line
    for y in range(1, max_size):
      dp1[y] = dp1.get(y, 0) + dp1.get(y - 1, 0)

    # merge `left' and `now'
    for y in range(1, max_size):
      dp1[y] = dp1.get(y, 0) + dp0.get(y, 0)

    # check and add 
    for y in range(1, max_size):
      # if `now' or `left' equal zero, and another more than zero.
      up = (dp0.get(y, 0) == 0 and dp1.get(y, 0) > 0) \
          or (dp0.get(y, 0) > 0 and dp1.get(y, 0) == 0)
      # if `now' or `under' equal zero, and another more than zero.
      left = (dp1.get(y - 1, 0) == 0 and dp1.get(y, 0) > 0) \
          or (dp1.get(y - 1, 0) > 0 and dp1.get(y, 0) == 0)
      # if `now' is more than zero.
      flag = dp1.get(y, 0) > 0

      perimeter += up + left
      size += flag

    dp0, dp1 = dp1, dict()

  print(size)
  if r == 2:
    print(perimeter)

Submission status: Runtime Error

Solution code:
class All_Column:
	def __init__(self, rec_num):
		self.rec_num = rec_num
		self.x_stack = []
		self.y_stack = [0 for i in range(10002)]
	
	def add(self, x, up, down):
		if self.y_stack[x+1] == 0:
			self.x_stack.append(x)
			self.y_stack[x+1] = One_Column(x, up, down)
		else:
			self.y_stack[x+1].add(up, down)
					
	def calc_menseki(self):
		self.x_stack.sort()
		menseki = 0
		for i in self.x_stack:
			for j in range(len(self.y_stack[i+1].up)):
				#print(i,j)
				menseki += (self.y_stack[i+1].up[j] - self.y_stack[i+1].down[j])
			#print("x: "+str(i)+", menseki: "+str(menseki))	
		#print("menseki: "+str(menseki))
		print(str(menseki))

	def calc_shuui(self):
		shuui = 0
		for i in self.x_stack:
			#print("x:"+str(i)+", rec num:"+str(len(self.y_stack[i+1].up)))
			one_shuui = 0
			#print("up + down: "+str((len(self.y_stack[i+1].up) + len(self.y_stack[i+1].down))))
			one_shuui += (len(self.y_stack[i+1].up) + len(self.y_stack[i+1].down))
			for j in range(len(self.y_stack[i+1].up)):
				edge = 2*(self.y_stack[i+1].up[j] - self.y_stack[i+1].down[j])
				# subtract edge
				for k in [i,i+2]:	
					if self.y_stack[k] != 0:
						for l in range(len(self.y_stack[k].up)):
							if (self.y_stack[k].down[l] <= self.y_stack[i+1].down[j]) and (self.y_stack[k].up[l] < self.y_stack[i+1].up[j]) and (self.y_stack[k].up[l] > self.y_stack[i+1].down[j]):
								#print("pass 1")
								edge -= (self.y_stack[k].up[l] - self.y_stack[i+1].down[j])
							elif (self.y_stack[k].down[l] >= self.y_stack[i+1].down[j]) and (self.y_stack[k].up[l] <= self.y_stack[i+1].up[j]):	 
								#print("pass 2")
								edge -= (self.y_stack[k].up[l] - self.y_stack[k].down[l])
							elif (self.y_stack[k].down[l] > self.y_stack[i+1].down[j]) and (self.y_stack[k].up[l] >= self.y_stack[i+1].up[j]) and (self.y_stack[k].down[l] < self.y_stack[i+1].up[j]):
								#print("pass 3")
								edge -= (self.y_stack[i+1].up[j] - self.y_stack[k].down[l])
							elif (self.y_stack[k].down[l] <= self.y_stack[i+1].down[j]) and (self.y_stack[k].up[l] >= self.y_stack[i+1].up[j]):
								#print("pass 4")
								edge -= (self.y_stack[i+1].up[j] - self.y_stack[i+1].down[j]) 
				one_shuui += edge
			#print("one shuui:"+str(one_shuui))	

			shuui += one_shuui	
		#print("shuui: "+str(shuui))							
		print(str(shuui))

class One_Column:		
	def __init__(self, x, up=None, down=None):
		self.x = x
		self.up = [up]
		self.down = [down]
	def add(self, up, down):
		append_flag =True
		for i in range(len(self.up)):
			if (down <= self.down[i]) and (up >= self.up[i]):
				del self.down[i]
				del self.up[i]
			elif (down < self.down[i]) and (up >= self.down[i]):
				self.down[i] = down
				append_flag =False
			elif (down <= self.up[i]) and (up > self.up[i]):
				self.up[i] = up
				append_flag = False
			elif (down >= self.down[i]) and (up <= self.up[i]):
				append_flag = False	
		if append_flag:	
			self.up.append(up)
			self.down.append(down)

		self.up.sort()
		self.down.sort()


flag =False
#for line in open("input.txt","r"):
while(1):
	line = input()
	line = line.rstrip("\n")
	#print(line)
	line_list = line.split(" ")  
	if(len(line_list) == 2):
		if flag:
			if option == 1:
				all_col.calc_menseki()
			elif option == 2: 	
				all_col.calc_menseki()
				all_col.calc_shuui()
		if (line_list[0] == "0") and (line_list[1] == "0"):
			break			
		flag = True	
		all_col = All_Column(int(line_list[0]))
		option = int(line_list[1])
	elif(len(line_list) == 4):
		for i in range(int(line_list[0]), int(line_list[2])):		# x1 ~ x2
			all_col.add(int(i), int(line_list[3]), int(line_list[1]))	# up = y2, down = y1

Submission status: Runtime Error

Solution code:
# coding: utf-8

field = []
for i in range(99):
	line = []
	for j in range(99):
		line.append(0)
	field.append(line)

while True:
	n, r = map(int, raw_input().split())
	if n == 0:
		break
	else:
		for _ in range(n):
			data = map(int, raw_input().split())
			x_start = data[0]
			y_start = data[1]
			x_end   = data[2]
			y_end   = data[3]
			for i in range(x_start, x_end):
				for j in range(y_start, y_end):
					field[i][j] = 1
		s = 0
		for i in range(len(field)):
			s += sum(field[i])
		if r == 1:
			print(s)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python

def readints(line):
    return map(int, line.split())


def mark(d, p):
    m = d.get(p, 0)
    d[p] = m + 1

def chunker(f):
    while True:
        line = f.readline()
        n, r = readints(line)
        if n == 0 and r == 0:
            raise StopIteration
        tiles = set()
        v_test = set()
        h_test = set()
        for i in range(n): 
            line = f.readline()
            lbx, lby, rtx, rty = readints(line)

            w = rtx - lbx 
            h = rty - lby
            for x in range(lbx, rtx): 
                for y in range(lby, rty): 
                    tiles.add((x,y))
            for x in range(lbx-1, rtx): 
                v_test.add((x, rty-1))
                v_test.add((x, lby-1))
            for y in range(lby-1, rty): 
                h_test.add((lbx-1, y))
                h_test.add((rtx-1, y))

                            
        area = len(tiles)
        if r == 1:
            yield area,
        elif r == 2:
            edge = 0
            for x, y in v_test:
                p = x, y
                q = x, y+1
                if p in tiles and q not in tiles or p not in tiles and q in tiles:
                    edge += 1
            for x, y in h_test:
                p = x, y
                q = x+1, y
                if p in tiles and q not in tiles or p not in tiles and q in tiles:
                    edge += 1

            yield area, edge

import sys

for ans in chunker(sys.stdin):
    if len(ans) == 1:
        print ans[0]
    elif len(ans) == 2:
        print ans[0]
        print ans[1]
    else:
        pass