Problem:


Matrix-like Computation

Your task is to develop a tiny little part of spreadsheet software.

Write a program which adds up columns and rows of given table as shown in the following figure:

Input

The input consists of several datasets. Each dataset consists of:

n (the size of row and column of the given table)
1st row of the table
2nd row of the table
 :
 :
nth row of the table

The input ends with a line consisting of a single 0.

Output

For each dataset, print the table with sums of rows and columns. Each item of the table should be aligned to the right with a margin for five digits. Please see the sample output for details.

Sample Input

4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
0

Output for the Sample Input

   52   96   15   20  183
   86   22   35   45  188
   45   78   54   36  213
   16   86   74   55  231
  199  282  178  156  815
   52   96   15   20  183
   86   22   35   45  188
   45   78   54   36  213
   16   86   74   55  231
  199  282  178  156  815



Sample input:
4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
0


Sample output:
   52   96   15   20  183
   86   22   35   45  188
   45   78   54   36  213
   16   86   74   55  231
  199  282  178  156  815
   52   96   15   20  183
   86   22   35   45  188
   45   78   54   36  213
   16   86   74   55  231
  199  282  178  156  815

Submission status: Accepted

Solution code:
import sys
def main():
    for line in sys.stdin:
        n = int(line)
        if n != 0:
            a = []
            for _ in range(n):
                a.append(list(map(int, input().split())))
            a.append(list(range(n + 1)))

            for x in range(n):
                hoge = 0
                for y in range(n):
                    hoge += a[y][x]
                else:
                    a[n][x] = hoge

            for x in range(n + 1):
                hoge = 0
                for y in range(n):
                    hoge += a[x][y]
                else:
                    if x != n:
                        a[x].append(hoge)
                    else:
                        a[n][n] = hoge

            for x in range(n + 1):
                for y in range(n + 1):
                    print("{0:5d}".format(a[x][y]), end = "")
                else:
                    print()

        else:
            break


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# Aizu Problem 0102: Matrix-like Computation
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


while True:
    N = int(input())
    if N == 0:
        break
    M = [[int(_) for _ in input().split()] for __ in range(N)]
    for i in range(N):
        M[i].append(sum(M[i]))
    last = [sum([M[row][col] for row in range(N)]) for col in range(N + 1)]
    M.append(last)
    fmt = "%5d" * (N + 1)
    for row in M:
        print(fmt % tuple(row))

Submission status: Accepted

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

    a = []
    for i in range(n):
        a.append([int(num) for num in input().split()])

    for i in range(n):
        sum = 0
        for j in range(n):
            sum += a[i][j]
        a[i].append(sum)


    a.append([])
    for i in range(n + 1):
        sum = 0
        for j in range(n):
            sum += a[j][i]
        a[n].append(sum)

    for i in range(n + 1):
        for j in range(n + 1):
            print('{0:>5}'.format(a[i][j]), end="")
        print()

Submission status: Accepted

Solution code:
import sys
import math

while True:
	n = int(input())
	if n == 0:
		break
	data = [list(map(int,input().split())) for i in range(n)]
	data.append([0 for i in range(n+1)])

	for i in range(n+1):
		if i != n:
			data[i].append(sum(data[i]))
		for j in range(n):
			data[n][i] = data[n][i]+data[j][i]
	for i in range(n+1):
		for j in range(n+1):
			if j != n:
				string = str('{:>5}'.format(data[i][j]))
				sys.stdout.write(string)
			else:
				print('{:>5}'.format(data[i][j]))

Submission status: Accepted

Solution code:
import sys
#from me.io import dup_file_stdin

def print2d(m):
    for r in m:
        print("".join(["{:5d}".format(x) for x in r]))

#@dup_file_stdin
def solve():
    while True:
        n = int(sys.stdin.readline())
        if n == 0 :
            return
        m = []
        for i in range(n):
            m.append([int(x) for x in sys.stdin.readline().split(' ')])
        for r in range(n):
            m[r].append(sum(m[r]))
        lastRow = []
        for c in range(n+1):
            s = 0
            for r in range(n):
                s += m[r][c]
            lastRow.append(s)
        m.append(lastRow)
        print2d(m)
solve()

Submission status: Accepted

Solution code:
while True:
    n = int(input())

    if n == 0:
        break

    matrix = [[] for _ in range(n)]
    col_sum = [0 for _ in range(n + 1)]
    for i in range(n):
        matrix[i] = list(map(int, input().split()))
        matrix[i].append(sum(matrix[i]))
        for j in range(n + 1):
            col_sum[j] += matrix[i][j]

    matrix.append(col_sum)

    for i in range(n + 1):
        for j in range(n + 1):
            print('%5d' % matrix[i][j], end='')
        print()

Submission status: Accepted

Solution code:
while True:
    n = int(input())
    if n == 0:
        break
    matrix = [list(map(int, input().split())) for _ in range(n)]
    for i in range(n):
        sum_ = sum(matrix[i])
        print(str("{:>5d}" * (n+1)).format(*matrix[i], sum_))
    sum_ = [sum(e) for e in list(zip(*matrix))]
    print(str("{:>5d}" * (n+1)).format(*sum_, sum(sum_)))

Submission status: Accepted

Solution code:
while True:
    inputCount = int(input())

    if inputCount == 0:
        break

    table = []

    for lp in range(inputCount):
        content = [int(item) for item in input().split(" ")]
        content.append(sum(content))
        table.append(content)

    table.append([])

    for col in range(inputCount + 1):
        total = 0
        for row in range(inputCount):
            total += table[row][col]

        table[inputCount].append(total)

    for array in table:
        print("".join("{:>5}".format(item) for item in array))

Submission status: Accepted

Solution code:
while 1:
 n=int(input())
 if n==0:break;
 a=[list(map(int,input().split()))for _ in[0]*n]
 for r in a:
  for s in r:print(f"{s:5}",end='')
  print(f"{sum(r):5}")
 for c in zip(*a):print(f"{sum(c):5}",end='')
 print(f"{sum([sum(r)for r in a]):5}")

Submission status: Accepted

Solution code:
while 1:
 n=int(input())
 if n==0:break;
 a=[]
 for _ in[0]*n:
  b=list(map(int,input().split()))
  b+=[sum(b)]
  a+=[b]
  for s in b:print("%5d"%s,end='')
  print()
 for c in zip(*a):print("%5d"%sum(c),end='')
 print()

Submission status: Accepted

Solution code:
while 1:
 n=int(input())
 if n==0:break;
 a=[]
 for i in range(n):
  a+=[list(map(int,input().split()))]
  a[i]+=[sum(a[i])]
  for s in a[i]:print("%5d"%s,end='')
  print()
 for c in zip(*a):print("%5d"%sum(c),end='')
 print()

Submission status: Accepted

Solution code:
while 1:
 n=int(input())
 if n==0:break;
 a=[]
 for i in range(n):
  b=list(map(int,input().split()))
  a+=[b+[sum(b)]]
  for s in a[i]:print("%5d"%s,end='')
  print()
 for c in zip(*a):print("%5d"%sum(c),end='')
 print()

Submission status: Accepted

Solution code:
while True:
    N = int(input())
    if N == 0:
        break

    table = [[0 for i in range(N+1)] for j in range(N+1)]

    for i in range(N):
        n = [int(i) for i in input().split()]
        for j in range(N):
            table[i][j] = n[j]

    for i in range(N):
        for j in range(N):
            table[i][N] += table[i][j]
            table[N][j] += table[i][j]

    for i in range(N):
        table[N][N] += table[i][N]

    for i in range(N+1):
        for j in range(N+1):
            print(str(table[i][j]).rjust(5), end="")
        print("")

Submission status: Accepted

Solution code:
while True:
    rows = []
    total = {}
    n = int(input())
    if (n == 0):
        break

    for r in range(n):
        datas = map(int, input().split())
        ds = list(datas)
        rows.append(ds)
            
    for r in range(n):
        s = 0
        for c in range(n):
            s += rows[r][c]
            if (c not in total):
                total[c] = rows[r][c]
            else:
                total[c] += rows[r][c]

        rows[r].append(s)
        if (n not in total):
            total[n] = s
        else:
            total[n] += s

    for r in range(n):
        for c in range(len(rows[r])):
            print("{0:>5}".format(rows[r][c]), end="")
        print()

    for t in range(len(total)):
        print("{0:>5}".format(total[t]), end="")
    print()

Submission status: Accepted

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

  mat = []
  for _ in range(n):
    lst = list(map(int, input().split()))
    lst.append(sum(lst))
    mat.append(lst)
  
  sum_lst = []
  for i in range(len(mat[0])):
    s = 0
    for j in range(n):
      s += mat[j][i]
    sum_lst.append(s)
  mat.append(sum_lst)

  for line in mat:
    put = ""
    for i in line:
      put += str(i).rjust(5)
    print(put)

Submission status: Accepted

Solution code:
while 1:
  l=[list(map(int,input().split())) for i in range(int(input()))]
  if not l:break
  le=len(l)
  for (i,j) in enumerate(l):
    l[i].append(sum(j))
  l.append([sum([l[k][i] for k in range(le)]) for i in range(le+1)])
  [print("".join([str(j).rjust(5) for j in i])) for i in l]

Submission status: Accepted

Solution code:
# AOJ 0102: Matrix-like Computation
# Python3 2018.6.17 bal4u

while True:
	n = int(input())
	if n == 0: break
	arr = [[0 for r in range(n+2)] for c in range(n+2)]

	for r in range(n):
		arr[r] = list(map(int, input().split()))
		arr[r].append(sum(arr[r]))

	for c in range(n+1):
		s = 0
		for r in range(n): s += arr[r][c]
		arr[n][c] = s

	for r in range(n+1):
		for c in range(n+1): print(format(arr[r][c], '5d'), end='')
		print()

Submission status: Accepted

Solution code:
import sys
while True:
  a=int(input())
  if a==0: break
  soug,tt,te=[0]*a,[],0
  for i in range(a):
    hoge=map(int,raw_input().split())
    te=0
    for j in range(a):
      te+=hoge[j]
      soug[j]+=hoge[j]
      sys.stdout.write("%5d"%hoge[j])
    else: sys.stdout.write("%5d"%te) ; print""
  else:
    te=0
    for i in range(a):
      sys.stdout.write("%5d"%soug[i])
      te+=soug[i]
    else: sys.stdout.write("%5d"%te)   ; print""

Submission status: Accepted

Solution code:
while 2 > 1:
	line_num = int(raw_input())
	if line_num < 1:
		break
	mylist = [0,0,0,0,0,0,0,0,0,0,0]
	for n in range(line_num):
		dat = map(int, raw_input().split(" "))
		col_num = len(dat)
		row_sum = 0
		for m in range(col_num):
			mylist[m] += dat[m]
			row_sum += dat[m]
		mylist[col_num] = row_sum
		disp = ""
		for m in range(col_num):
			disp += ("%s" % dat[m]).rjust(5)
		disp += ("%s" % row_sum).rjust(5)
		print disp
	mylist[col_num] = 0
	for m in range(col_num):
		mylist[col_num] += mylist[m]
	disp_sum = ""
	for m in range(col_num + 1):
		disp_sum += ("%s" % mylist[m]).rjust(5)
	print disp_sum

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def solve():
    while True:
        n = input()
        if n > 0:
            mat = [[0 for i in xrange(n + 1)] for j in xrange(n + 1)]
            for i in range(n):
                line = sys.stdin.readline().split()
                for j in range(n):
                    mat[i][j] = int(line[j])
            for i in xrange(n):
                mat[i][n] = sum(mat[i][j] for j in range(n))
                mat[n][i] = sum(mat[j][i] for j in range(n))
            mat[n][n] = sum(mat[n][i] for i in range(n))
            for lst in mat:
                print "".join(map(lambda n: "%5d" % n, lst))
        else:
            sys.exit()

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
R = lambda:map(int,raw_input().split())

while 1:
    n = int(raw_input())
    if n == 0: break
    lst = []
    for i in xrange(n):
        lst.append(R())
        lst[i].append(sum(lst[i]))
    s = []
    for i in xrange(n+1):
        t = 0
        for j in xrange(n):
            t += lst[j][i]
        s.append(t)

    for i in xrange(n):
        for j in xrange(n+1):
            lst[i][j] = str(lst[i][j]).rjust(5)
    for i in xrange(n+1):
        s[i] = str(s[i]).rjust(5)
    lst.append(s)
    #print lst
    for i in xrange(n+1):
        print "".join(lst[i])

Submission status: Accepted

Solution code:
import sys

while True:
    n = int(raw_input())
    if n == 0: break
    
    a = []
    for i in range(n):
        a.append(map(int, raw_input().split()))
    
    for i in range(n):
        a[i].append(sum(a[i]))
    
    col_sum = []
    for col in range(len(a[0])):
        s = 0
        for row in range(len(a)):
            s += a[row][col];
        col_sum.append(s)
    a.append(col_sum)

    for row in range(len(a)):
        for col in range(len(a[0])):
            sys.stdout.write("%5d" % a[row][col])
        print

Submission status: Accepted

Solution code:
while True:
    n=input()
    if n==0:
        break
    li=[[0]*(n+1) for unused in xrange(n+1)]
    for i in xrange(n):
        li[i][:n]=map(int,raw_input().split())
    for i in xrange(n):
        li[i][n]=sum(li[i])
        li[n][i]=sum([li[j][i] for j in xrange(n)])
    li[n][n]=sum(li[n])
    print "\n".join(["".join(map(lambda x:str(x).rjust(5),li[i])) for i in xrange(n+1)])

Submission status: Accepted

Solution code:
def print_nums(nums):
    print ''.join(['%5d' % num for num in nums])

while 1:
    n = int(raw_input())
    if n == 0: break
    sums = [0] * (n + 1)
    for i in range(n):
        nums = map(int, raw_input().split())
        nums.append(sum(nums))
        print_nums(nums)
        for j in range(n + 1):
            sums[j] += nums[j]
    print_nums(sums)

Submission status: Accepted

Solution code:
#coding:utf-8
ans=[]
while True:
    curAns=[]
    n=input()
    if n ==0:
        break
    for i in xrange(n):
        lst=map(int,raw_input().split())
        lst.append(sum(lst))
        curAns.append(lst)
    lLst=[]                             #最後のリスト
    for i in xrange(n+1):               #横方向探索
        verSum=0
        for j in xrange(n):             #縦方向探索
            verSum+=curAns[j][i]
        lLst.append(verSum)
    curAns.append(lLst)
    relAns=[]
    for i in curAns:
        tmpLst=map(str,i)
        nLst=[]
        for j in tmpLst:
            nLst.append(j.rjust(5))
        ansStr=''.join(nLst)
        relAns.append(ansStr)
    ans.append(relAns)

for i in ans:
    for j in i:
        print j

Submission status: Accepted

Solution code:
import sys
f=lambda v,b: v.append(sum(b))
while True:
    c=input()
    if c==0: break
    x=range(c)
    z=range(c+1)
    q={}
    for i in x:
        q[i]=map(int,raw_input().split())
        t=q.values()[i]
        f(t,t)
    q[i+1]=[]
    for g in x:
        w=[]
        for j in x:
            w.append(q.values()[j][g]) 
        f(q[i+1],w)
    t=q[i+1]
    f(t,t)
    for i in q.values():
        for j in z:
            sys.stdout.write("%5d"%i[j])
        print

Submission status: Accepted

Solution code:
import sys
f=lambda v,b: v.append(sum(b))
while True:
    c=input()
    if c==0: break
    x=range(c);z=range(c+1);q={}
    for i in x:
        q[i]=map(int,raw_input().split());t=q.values()[i];f(t,t)
    q[i+1]=[]
    for g in x:
        w=[]
        for j in x:
            w.append(q.values()[j][g]) 
        f(q[i+1],w)
    t=q[i+1];f(t,t)
    for i in q.values():
        for j in z: sys.stdout.write("%5d"%i[j])
        print

Submission status: Accepted

Solution code:

import sys


def solv(matrix):
    for row in matrix:
        s = sum(row)
        row.append(s)
    r = []
    l = len(matrix[0])
    for c in range(l):
        column = map(lambda x: x[c], matrix)
        sc = sum(column)
        r.append(sc)
    matrix.append(r)
    return matrix


while True:
    n = int(sys.stdin.readline())
    if n == 0:
        exit()
    matrix = []
    for i in range(n):
        line = sys.stdin.readline()
        row = map(int, line.split(' '))
        matrix.append(row)
    matrix2 = solv(matrix)
    for row in matrix2:
        print ''.join(map(lambda x: str(x).rjust(5), row))

Submission status: Accepted

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break

    a = [[] for i in range(n + 1)]

    for i in range(n + 1):
        if i < n:
            a[i] = map(int, raw_input().split())
            a[i].append(sum(a[i]))
        else:
            a[i] = [sum([a[j][k] for j in range(n)]) for k in range(n + 1)]

    s = ""
    for i in range(n + 1):
        for j in range(n + 1):
            s += "{0:5d}".format(a[i][j])
        s += "\n"
    print s,

Submission status: Accepted

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break

    a = [[] for i in range(n + 1)]
    for i in range(n + 1):
        if i < n:
            a[i] = map(int, raw_input().split())
            a[i].append(sum(a[i]))
        else:
            a[i] = [sum([a[j][k] for j in range(n)]) for k in range(n + 1)]

    s = ""
    for i in range(n + 1):
        s += "".join(map(lambda x: str(x).rjust(5, " "), a[i])) + "\n"
    print s,

Submission status: Accepted

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break

    a = [[] for i in range(n + 1)]
    for i in range(n + 1):
        if i < n:
            a[i] = map(int, raw_input().split())
            a[i].append(sum(a[i]))
        else:
            a[i] = [sum([a[j][k] for j in range(n)]) for k in range(n + 1)]

    for i in range(n + 1):
        print "".join(map(lambda x: str(x).rjust(5, " "), a[i])) + "\n",

Submission status: Accepted

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break

    a = []
    for i in range(n + 1):
        if i < n:
            a.append(map(int, raw_input().split()))
            a[i].append(sum(a[i]))
        else:
            a.append([sum([a[j][k] for j in range(n)]) for k in range(n + 1)])

    for aa in a:
        print ''.join(map(lambda x: str(x).rjust(5, ' '), aa)) + '\n',

Submission status: Accepted

Solution code:
import sys

def solve():
    while True:
        n = input()
        if n > 0:
            mat = [[0 for i in xrange(n + 1)] for j in xrange(n + 1)]
            for i in range(n):
                line = sys.stdin.readline().split()
                for j in range(n):
                    mat[i][j] = int(line[j])
            for i in xrange(n):
                mat[i][n] = sum(mat[i][j] for j in range(n))
                mat[n][i] = sum(mat[j][i] for j in range(n))
            mat[n][n] = sum(mat[n][i] for i in range(n))
            for lst in mat:
                print "".join(map(lambda n: "%5d" % n, lst))
        else:
            sys.exit()

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, exit


def main(readline=stdin.readline):
    fmt = '{:5d}'.format

    while 1:
        n = int(readline())
        if not n:
            exit()

        total = [0] * (n+1)

        for _ in range(n):
            s = 0
            for i, val in enumerate(int(d) for d in readline().split()):
                total[i] += val
                s += val
                print(fmt(val), end='')
            total[-1] += s
            print(fmt(s))

        print(''.join(fmt(i) for i in total))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(raw_input())
while n != 0:
	a = [map(int,raw_input().split()) for i in xrange(n)]
	a = [l + [sum(l)] for l in a]
	a.append([sum([l[i] for l in a]) for i in xrange(len(a[0]))])
	print '\n'.join([''.join([str(i).rjust(5) for i in l]) for l in a])
	n = int(raw_input())

Submission status: Accepted

Solution code:
while True:
	n = int(raw_input())
	if n == 0: break
	ls = [map(int, raw_input().split()) for i in range(n)]+[[0]*(n+1)]
	for i in range(n):
		ls[i].append(sum(ls[i]))
	for i in range(n+1):
		for j in range(n):
			ls[n][i] += ls[j][i]
	for row in ls:
		print ''.join(map(lambda x: str(x).rjust(5), row))

Submission status: Accepted

Solution code:
while True:
	n = input()
	if n == 0: break
	ls = [map(int, raw_input().split())+[0] for i in range(n)]+[[0]*(n+1)]
	for row in range(n+1):
		for col in range(n):
			ls[n][col] += ls[row][col] if row != n else 0
			ls[row][n] += ls[row][col]
		print "".join(map(lambda x: str(x).rjust(5), ls[row]))

Submission status: Accepted

Solution code:
while 1:
	n = input()
	if n == 0: break
	l = [map(int, raw_input().split())+[0] for i in range(n)]+[[0]*(n+1)]
	for r in range(n+1):
		for c in range(n):
			l[n][c] += l[r][c] if r != n else 0
			l[r][n] += l[r][c]
		print "".join(map(lambda x: str(x).rjust(5), l[r]))

Submission status: Accepted

Solution code:
while True:
    n = input()
    ans = []
    if n == 0: break
    tmp = [0] * (n+1)
    for i in range(n):
        ans.append(map(int, raw_input().split()))
        ans[i].append(sum(ans[i]))
        for j in range(len(ans[i])):
            tmp[j] += ans[i][j]
    ans.append(tmp)
    for a in ans:
        print "".join(map(lambda x: str(x).rjust(5), a))

Submission status: Accepted

Solution code:
while True:
    A = []
    n = int(input())
    if n == 0:
        break
    for i in range(n):
        A.append(list(map(int,input().split())))
    result = A[:]
    result_T = list(map(list,zip(*A)))
    for line in result:
        line.append(sum(line))
        
    for line in result_T:
        line.append(sum(line))

    result_T = list(map(list,zip(*result_T)))
    result.append(result_T[-1]+[sum(result_T[-1])])
    
    for i in range(len(result)):
        for j in range(len(result[i])):
            print(str(result[i][j]).rjust(5),end="")
        print()

Submission status: Accepted

Solution code:
while True :
    n = int(input())
    if n == 0 :
        break
    
  
    L = [0] * n
    for i in range(n) :
        tmp = list(map(int, input().split()))
        for j in range(n) :
            L[j] += tmp[j]
        tmp.append(sum(tmp))
        for j in range(n+1) :
            print(str(tmp[j]).rjust(5), end = "")
        print()
    L.append(sum(L))
    for j in range(n+1) :
        print(str(L[j]).rjust(5), end = "")
    print()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write

fmt = "{:5d}".format
def solve():
    N = int(readline())
    if N == 0:
        return False
    A = [list(map(int, readline().split())) for i in range(N)]
    for ln in A:
        write("".join(map(fmt, ln)))
        write(fmt(sum(ln)))
        write("\n")
    b = [sum(A[i][j] for i in range(N)) for j in range(N)]
    write("".join(map(fmt, b)))
    write(fmt(sum(b)))
    write("\n")
    return True
while solve():
    ...

Submission status: Accepted

Solution code:
while(1):
    n = int(input())
    if n == 0:
        break
    t = [[0] * (n + 1) for i in range(n + 1)]
    m = []
    for i in range(0,n):
        m.append(list(int(x) for x in input().split(" ")))
    sum = 0
    for i in range(0,n):
        sum1 = 0
        sum2 = 0
        for j in range(0,n):
            t[i][j] = m[i][j]
            sum1 += m[i][j]
            sum2 += m[j][i]
        t[i][n] = sum1
        t[n][i] = sum2
        sum += sum1
    t[n][n] = sum
    
    
    for i in range(0,n + 1):
        for j in range(0,n + 1):
            print("%5d" %(t[i][j]),end="")
        print()

Submission status: Accepted

Solution code:
while True:
    n=int(input())
    if n==0:
        break
    i=0
    mat=[]
    #リストを一つに
    while i<n:
        tmp_mat=list(map(int, input().split()))
        mat.extend(tmp_mat)
        i+=1
    total=0
    tmp_last=[0 for l in range(n+1)]
    for x in range(len(mat)):
        total+=mat[x]
        tmp_last[x%n]+=mat[x]
        print(str(mat[x]).rjust(5),end="")
        if x%n==n-1:
            tmp_last[n]+=total
            print(str(total).rjust(5))
            total=0
    for y in range(n+1):
        print(str(tmp_last[y]).rjust(5),end="")
    print("")

Submission status: Accepted

Solution code:
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop
import copy
from test.support import _MemoryWatchdog

BIG_NUM = 2000000000
HUGE_NUM = 99999999999999999
MOD = 1000000007
EPS = 0.000000001
sys.setrecursionlimit(100000)


SIZE = 51
table = [[None]*SIZE for _ in range(SIZE)]

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

    for row in range(N+1):
        for col in range(N+1):
            table[row][col] = 0

    sum = 0

    for row in range(N):
        input_array = list(map(int,input().split()))
        for col in range(N):
            table[row][col] += input_array[col]
            table[N][col] += input_array[col]
            table[row][N] += input_array[col]
            sum += input_array[col]

    table[N][N] = sum

    for row in range(N+1):
        for col in range(N+1):
            print("%5d"%(table[row][col]),end="")
        print()

Submission status: Accepted

Solution code:
while True:
	n = int(input())
	if n == 0: break
	arr = [[0 for r in range(n+2)] for c in range(n+2)]

	for r in range(n):
		arr[r] = list(map(int, input().split()))
		arr[r].append(sum(arr[r]))

	for c in range(n+1):
		s = 0
		for r in range(n): s += arr[r][c]
		arr[n][c] = s

	for r in range(n+1):
		for c in range(n+1): print(format(arr[r][c], '5d'), end='')
		print()

Submission status: Accepted

Solution code:
while 1:
    n = int(input())
    if n == 0:
        break
    L = []
    for i in range(n):
        L += [list(map(int,input().split()))+[0]]
    L += [[0]*(n+1)]
    for r in range(n):
        for c in range(n):
            L[r][n] += L[r][c]
            L[n][c] += L[r][c]
            L[n][n] += L[r][c]
    for f in range(n+1):
        for h in range(n+1):
            L[f][h] = str(L[f][h]).rjust(5)
        print (''.join(L[f]))

Submission status: Accepted

Solution code:

while True:
    L = []
    n = int(input())
    if n == 0:
        break
    for _ in range(n):
        l = [int(x) for x in input().split()]
        l.append(sum(l))
        L.append(l)

    l = []
    for i in range(len(L[0])):
        s = []
        for j in range(len(L)):
            s.append(L[j][i])
        l.append(sum(s))
    L.append(l)

    for l in L:
        for i in l:
            print("{:>5d}".format(i),end="")
        print()

Submission status: Accepted

Solution code:
while True:
  n = int(input())
  if n==0:
    break
  A=[]
  for a in range(n):
    x =list(map(int, input().split()))
    x.append(sum(x))
    A.append(x)
  Y=[]
  for j in range(n+1):
    y=0
    for i in range(n):
      y+=A[i][j]
    Y.append(y)

  A.append(Y)
  
  for i in range(n+1):
    for j in range(n+1):
      a=A[i][j]
      a=str(a)
      a=a.rjust(5)
      print(a,end="")
    print()

Submission status: Accepted

Solution code:
while True:
    n = int(input())
    if n == 0:
        break
    arr = [[0 for r in range(n+2)]for c in range(n+2)]
    
    for r in range(n):
        arr[r] = list(map(int, input().split()))
        arr[r].append(sum(arr[r]))

    for c in range(n+1):
        s = 0
        for r in range(n):
            s += arr[r][c]
        arr[n][c] = s
    
    for r in range(n+1):
        for c in range(n+1):
            print(format(arr[r][c],'5d'), end ='')
        print()

Submission status: Accepted

Solution code:
# coding=utf-8

###
### for python program
###

import sys
import math

# math class
class mymath:
    ### pi
    pi = 3.14159265358979323846264338

    ### Prime Number
    def pnum_eratosthenes(self, n):
        ptable = [0 for i in range(n+1)]
        plist = []

        for i in range(2, n+1):
            if ptable[i]==0:
                plist.append(i)
                for j in range(i+i, n+1, i):
                    ptable[j] = 1
        return plist

    ### GCD
    def gcd(self, a, b):
        if b == 0:
            return a
        return self.gcd(b, a%b)

    ### LCM
    def lcm(self, a, b):
        return (a*b)//self.gcd(a,b)

    ### Mat Multiplication
    def mul(self, A, B):
        ans = []
        for a in A:
            c = 0
            for j, row in enumerate(a):
                c += row*B[j]
            ans.append(c)
        return ans

mymath = mymath()

### output class
class output:
    ### list
    def list(self, l):
        l = list(l)
        #print(" ", end="")
        for i, num in enumerate(l):
            print(num, end="")
            if i != len(l)-1:
                print(" ", end="")
        print()

output = output()

### input sample
#i = input()
#N = int(input())
#A, B, C = [x for x in input().split()]
#N, K = [int(x) for x in input().split()]
#inlist = [int(w) for w in input().split()]

#R = float(input())
#A.append(list(map(int,input().split())))

#for line in sys.stdin.readlines():
#    x, y = [int(temp) for temp in line.split()]

#abc list
#abc = [chr(ord('a') + i) for i in range(26)]

### output sample
# print("{0} {1} {2:.5f}".format(A//B, A%B, A/B))
# print("{0:.6f} {1:.6f}".format(R*R*math.pi,R*2*math.pi))
# print(" {}".format(i), end="")

# def printA(A):
#     for i, n in enumerate(A):
#         print(n, end='')
#         if i != N-1:
#             print(' ', end='')
#     print()

# リスト内包表記 ifあり
# [x-k if x != 0 else x for x in C]

# ソート
# N = N.sort()

# 10000個の素数リスト
# P = mymath.pnum_eratosthenes(105000)

def get_input():
    N = []
    while True:
        try:
            N.append(input())
            #N.append(int(input()))
            #N.append(float(input()))
        except EOFError:
            break
    return N

def is_integer(n):
    try:
        float(n)
    except ValueError:
        return False
    else:
        return float(n).is_integer()

def dist(A, B):
    d = 0
    for i in range(len(A)):
        d += (A[i]-B[i])**2            
    d = d**(1/2)
    return d

while True:
    N = int(input())
    A = []

    if N == 0:
        break

    for i in range(N):
        A.append([int(x) for x in input().split()])

    for i in range(N):
        A[i].append(sum(A[i]))

    B = []

    for i in range(N+1):
        temp = 0
        for j in range(N):
            temp += A[j][i]
        B.append(temp)
    A.append(B)

    for row in A:
        for i in row:
            s = str(i)
            print(s.rjust(5, ' '), end='')
        print()
        pass

Submission status: Accepted

Solution code:
while True:
    n=int(input())
    if n==0:
        break
    
    ts=[0]*n
    ys=0
    a=[]
    for i in range(n):
        b=list(map(int,input().split()))
        s=sum(b)
        a.append(b+[s])
        for i in range(n):
            ts[i]+=b[i]
        ys+=s
    t=sum(ts)
    for i in range(n):
        for j in range(n+1):
            print(str(a[i][j]).rjust(5),end='')
        print()

    for i in range(n):
        print(str(ts[i]).rjust(5),end='')
    print(str(t).rjust(5))

Submission status: Accepted

Solution code:
while 1:
    try:
        N=int(input())
        if N==0:break
        matrix = [list(map(int,input().split())) for i in range(N)]
        matrix.append([])
        for i in range(N):matrix[i].append(sum(matrix[i]))
        for j in range(len(matrix)):
            pointer=0
            for k in range(N):
                pointer +=matrix[k][j]
            matrix[N].append(pointer)
        for i in range(N+1):
            for j in range(N+1):
                print(str(matrix[i][j]).rjust(5), end="")
            print()
    except:break