Problem:


Score : 800 points

Problem Statement

There is a grid with R rows and C columns.
We call the cell in the r-th row and c-th column (r，c).

Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i，c_i) for each i (1≤i≤N).
After that he fell asleep.

Mr. Aoki found the grid and tries to surprise Mr. Takahashi by writing integers into all remaining cells.
The grid must meet the following conditions to really surprise Mr. Takahashi.

Condition 1: Each cell contains a non-negative integer.

Condition 2: For any 2×2 square formed by cells on the grid, the sum of the top left and bottom right integers must always equal to the sum of the top right and bottom left integers.

Determine whether it is possible to meet those conditions by properly writing integers into all remaining cells.

Constraints

2≤R，C≤10^5

1≤N≤10^5

1≤r_i≤R

1≤c_i≤C

(r_i，c_i) ≠ (r_j，c_j) (i≠j)

a_i is an integer.

0≤a_i≤10^9

Input

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

R C
N
r_1 c_1 a_1
r_2 c_2 a_2
:
r_N c_N a_N

Output

Print Yes if it is possible to meet the conditions by properly writing integers into all remaining cells.
Otherwise, print No.

Sample Input 1

2 2
3
1 1 0
1 2 10
2 1 20

Sample Output 1

Yes

You can write integers as follows.

Sample Input 2

2 3
5
1 1 0
1 2 10
1 3 20
2 1 30
2 3 40

Sample Output 2

No

There are two 2×2 squares on the grid, formed by the following cells:

Cells (1，1), (1，2), (2，1) and (2，2)

Cells (1，2), (1，3), (2，2) and (2，3)

You have to write 40 into the empty cell to meet the condition on the left square, but then it does not satisfy the condition on the right square.

Sample Input 3

2 2
3
1 1 20
1 2 10
2 1 0

Sample Output 3

No

You have to write -10 into the empty cell to meet condition 2, but then it does not satisfy condition 1.

Sample Input 4

3 3
4
1 1 0
1 3 10
3 1 10
3 3 20

Sample Output 4

Yes

You can write integers as follows.

Sample Input 5

2 2
4
1 1 0
1 2 10
2 1 30
2 2 20

Sample Output 5

No

All cells already contain a integer and condition 2 is not satisfied.



Sample input:
2 2
3
1 1 0
1 2 10
2 1 20


Sample output:
Yes

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
VectorSet = set() 
Grid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	Grid[("R", r)].append((("C", c), a))
	Grid[("C", c)].append((("R", r), a))
	VectorSet.add(('R', r))
	VectorSet.add(('C', c))

def iteration(vector):
	VectorSet.discard(vector)
	for (v, a) in Grid[vector]:
		temp = a - VectorCover[vector]
		if (v in VectorCover):
			if(temp != VectorCover[v]):
				print("No")
				print("No equal")
				exit()
		else:
			VectorCover[v] = temp
			iteration(v) 

while(len(VectorSet) != 0):
	vector = VectorSet.pop()
	VectorCover = dict() 
	VectorCover[vector] = 0
	iteration(vector)
	minR = min(a for (p, a) in VectorCover.items() if (p[0] == "R"))
	minC = min(a for (p, a) in VectorCover.items() if (p[0] == "C"))
	if (minR + minC < 0):
		print("No")
		print("min")
		exit()
		
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
VectorSet = set() 
Grid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	Grid[("R", r)].append((("C", c), a))
	Grid[("C", c)].append((("R", r), a))
	VectorSet.add(('R', r))
	VectorSet.add(('C', c))

def iteration(vector):
	VectorSet.discard(vector)
	for (v, a) in Grid[vector]:
		temp = a - VectorCover[vector]
		if (v in VectorCover):
			if(temp is not VectorCover[v]):
				print("No")
				exit()
		else:
			VectorCover[v] = temp
			iteration(v) 

while(len(VectorSet) is not 0):
	vector = VectorSet.pop()
	VectorCover = defaultdict(int)
	VectorCover[vector] = 0
	iteration(vector)
	minR = min(a for (p, a) in VectorCover.items() if (p[0] is "R"))
	minC = min(a for (p, a) in VectorCover.items() if (p[0] is "C"))
	if (minR + minC < 0):
		print("No")
		exit()
		
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
VectorSet = set() 
Grid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	Grid[("R", r)].append((("C", c), a))
	Grid[("R", c)].append((("R", r), a))
	VectorSet.add(('R', r))
	VectorSet.add(('C', c))

def iteration(vector):
	VectorSet.discard(vector)
	for (v, a) in Grid[vector]:
		temp = a - VectorCover[vector]
		if (v in VectorCover):
			if(temp is not VectorCover[v]):
				print("No")
				exit()
		else:
			VectorCover[v] = temp
			iteration(v) 

while(len(VectorSet) is not 0):
	vector = VectorSet.pop()
	VectorCover = defaultdict(int)
	VectorCover[vector] = 0
	iteration(vector)
	minR = min(a for (p, a) in VectorCover.items() if (p[0] is "R"))
	minC = min(a for (p, a) in VectorCover.items() if (p[0] is "C"))
	if (minR + minC < 0):
		print("No")
		exit()
		
print("Yes")

Submission status: Wrong Answer

Solution code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
VectorCover = defaultdict(int)
VectorSet = set() 
Grid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	Grid[("R", r)].append((("C", c), a))
	Grid[("R", c)].append((("R", r), a))
	VectorSet.add(('R', r))
	VectorSet.add(('C', c))

def iteration(vector):
	VectorSet.discard(vector)
	for (v, a) in Grid[vector]:
		temp = a - VectorCover[vector]
		if (v in VectorCover):
			if(temp is not VectorCover[v]):
				print("No")
				exit()
		else:
			VectorCover[v] = temp
			iteration(v) 

while(len(VectorSet) is not 0):
	vector = VectorSet.pop()
	VectorCover[vector] = 0
	iteration(vector)
	minR = min(a for (p, a) in VectorCover.items() if (p[0] is "R"))
	minC = min(a for (p, a) in VectorCover.items() if (p[0] is "C"))
	if (minR + minC < 0):
		print("No")
		exit()
		
print("Yes")

Submission status: Wrong Answer

Solution code:
#/usr/bin/env python3
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def readInput():
	return [int(i) for i in input().split(" ")]

(R, C) = readInput()
N = int(input())
rowIdx = list() 
grid = defaultdict(list)
rowGrid = defaultdict(list)
colGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].append(c)
	grid[(r, c)] = a 
	rowIdx.append(r)

for i in rowIdx:
	if(len(rowGrid[i]) != 1):
		r = i
		break
diff = grid[(r,rowGrid[r][0])] - grid[(r,rowGrid[r][1])]
for rowNum in rowIdx:
	tempRow = rowGrid[rowNum]
	anchor = grid[(rowNum, tempRow[0])]
	for col in range(0,tempRow[0]):
		pair = grid[(rowNum, col)]
		if(pair == [] and anchor < -diff):
			print('No')
			exit()
		elif(pair != [] and (pair - anchor) != diff):
			print('No')
			exit() 
	for col in range(tempRow[0]+1,C):
		pair = grid[(rowNum, col)]
		if(pair == [] and anchor < diff ): 
			print('No')
			exit()
		if(pair != [] and (anchor - pair) != diff):
			print('No')
			exit() 
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
RowIdx = set()
ColIdx = set()
CoverGrid = set()
Grid = defaultdict(list)
RowGrid = defaultdict(list)
ColGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	RowGrid[r].append(c)
	ColGrid[c].append(r)
	Grid[(r, c)] = a
	RowIdx.add(r)
	ColIdx.add(c)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row]
		TempCol = TempRow.copy()
		for pointer in TempRow:
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = ColGrid[pointer].copy()
				ObjCol.remove(row)
				for obj in ObjCol:
					val = Grid[(obj, pointer)]- dif 
					if (val < 0):
						print("No")
						exit()
					if ((obj, pair) in Grid):
						if (val != Grid[(obj, pair)]):
							print("No");
							exit()
						else:
							continue
					else:
						Grid[(obj, pair)] = val
						RowGrid[obj].append(pair)
						ColGrid[pair].append(obj)
						fresh = 1
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
RowIdx = set()
ColIdx = set()
CoverGrid = set()
Grid = defaultdict(list)
RowGrid = defaultdict(list)
ColGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	RowGrid[r].append(c)
	ColGrid[c].append(r)
	Grid[(r, c)] = a
	RowIdx.add(r)
	ColIdx.add(c)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row].copy()
		for pointer in TempRow:
			TempRow.remove(pointer)
			for pair in TempRow:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = ColGrid[pointer].copy()
				ObjCol.remove(row)
				for obj in ObjCol:
					val = Grid[(obj, pointer)]- dif 
					if (val < 0):
						print("No")
						exit()
					if ((obj, pair) in Grid):
						if (val != Grid[(obj, pair)]):
							print("No");
							exit()
						else:
							continue
					else:
						Grid[(obj, pair)] = val
						RowGrid[obj].append(pair)
						ColGrid[pair].append(obj)
						fresh = 1
print("Yes")

Submission status: Wrong Answer

Solution code:
import numpy as np

R, C = map(int, raw_input().split())
N = int(raw_input())
rca_list = []


for i in range(N):
    rca_list.append(map(int, raw_input().split()))
    

# ret
ret = "Yes"


while len(rca_list) > 0 and ret == "Yes":
    
    # 
    r_vec = np.zeros(R)
    r_vec_2 = np.zeros(R)
    c_vec = np.zeros(C)
    c_vec_2 = np.zeros(C)


    # first square
    r, c, a = rca_list.pop()

    r_vec[r-1] = a
    c_vec[c-1] = 0
    r_vec_2[r-1] = 1
    c_vec_2[c-1] = 1

    go_flg = "Yes"
    while go_flg == "Yes" and ret == "Yes":
        go_flg = "No"
        for i in range(len(rca_list)-1, -1, -1):
            r, c, a = rca_list[i]
            # filled
            if r_vec_2[r-1] + c_vec_2[c-1] == 2:
                rca_list.pop(i)
                go_flg = "Yes"
                if c != r_vec[r-1] + c_vec[c-1]:
                    ret = "No"
            elif r_vec_2[r-1] + c_vec_2[c-1] == 1:
                if r_vec_2[r-1] == 1:
                    c_vec_2[c-1] = 1
                    c_vec[c-1] = a - r_vec[r-1]
                    rca_list.pop(i)
                    go_flg = "Yes"
                elif c_vec_2[c-1] == 1:
                    r_vec_2[r-1] = 1
                    r_vec[r-1] = a - c_vec[c-1]
                    rca_list.pop(i)
                    go_flg = "Yes"
            else:
                pass
            
    if min(r_vec[r_vec_2==1]) + min(c_vec[c_vec_2==1]) < 0:
        ret = "No"
    
print ret

Submission status: Wrong Answer

Solution code:
import numpy as np

R, C = map(int, raw_input().split())
N = int(raw_input())
rca_list = []


for i in range(N):
    rca_list.append(map(int, raw_input().split()))
    

# ret
ret = "YES"


while len(rca_list) > 0 and ret == "YES":
    
    # 
    r_vec = np.zeros(R)
    r_vec_2 = np.zeros(R)
    c_vec = np.zeros(C)
    c_vec_2 = np.zeros(C)


    # first square
    r, c, a = rca_list.pop()

    r_vec[r-1] = a
    c_vec[c-1] = 0
    r_vec_2[r-1] = 1
    c_vec_2[c-1] = 1

    go_flg = "YES"
    while go_flg == "YES" and ret == "YES":
        go_flg = "NO"
        for i in range(len(rca_list)-1, -1, -1):
            r, c, a = rca_list[i]
            # filled
            if r_vec_2[r-1] + c_vec_2[c-1] == 2:
                rca_list.pop(i)
                go_flg = "YES"
                if c != r_vec[r-1] + c_vec[c-1]:
                    ret = "NO"
            elif r_vec_2[r-1] + c_vec_2[c-1] == 1:
                if r_vec_2[r-1] == 1:
                    c_vec_2[c-1] = 1
                    c_vec[c-1] = a - r_vec[r-1]
                    rca_list.pop(i)
                    go_flg = "YES"
                elif c_vec_2[c-1] == 1:
                    r_vec_2[r-1] = 1
                    r_vec[r-1] = a - c_vec[c-1]
                    rca_list.pop(i)
                    go_flg = "YES"
            else:
                pass
            
    if min(r_vec[r_vec_2==1]) + min(c_vec[c_vec_2==1]) < 0:
        ret = "NO"
    
print ret

Submission status: Wrong Answer

Solution code:
import numpy as np

R, C = map(int, raw_input().split())
N = int(raw_input())
rca_list = []


for i in range(N):
    rca_list.append(map(int, raw_input().split()))
    
r_vec = np.zeros(R)
r_vec_2 = np.zeros(R)
c_vec = np.zeros(C)
c_vec_2 = np.zeros(C)

# ret
ret = "YES"


while len(rca_list) > 0 and ret == "YES":
    # first square
    r, c, a = rca_list.pop()

    r_vec[r-1] = a
    c_vec[c-1] = 0
    r_vec_2[r-1] = 1
    c_vec_2[c-1] = 1

    go_flg = "YES"
    while go_flg == "YES" and ret == "YES":
        go_flg = "NO"
        for i in range(len(rca_list)-1, -1, -1):
            r, c, a = rca_list[i]
            # filled
            if r_vec_2[r-1] + c_vec_2[c-1] == 2:
                rca_list.pop(i)
                go_flg = "YES"
                if c != r_vec[r-1] + c_vec[c-1]:
                    ret = "NO"
            elif r_vec_2[r-1] + c_vec_2[c-1] == 1:
                if r_vec_2[r-1] == 1:
                    c_vec_2[c-1] = 1
                    c_vec[c-1] = a - r_vec[r-1]
                    rca_list.pop(i)
                    go_flg = "YES"
                elif c_vec_2[c-1] == 1:
                    r_vec_2[r-1] = 1
                    r_vec[r-1] = a - c_vec[c-1]
                    rca_list.pop(i)
                    go_flg = "YES"
            else:
                pass
            
if ret == "YES" and min(r_vec) + min(c_vec) >= 0:
    print "YES"
else:
    print "NO"

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
RowIdx = set()
ColIdx = set()
Grid = defaultdict(list)
RowGrid = defaultdict(list)
ColGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	RowGrid[r].append(c)
	ColGrid[c].append(r)
	Grid[(r, c)] = a
	RowIdx.add(r)
	ColIdx.add(c)	
#print(RowIdx)
#print(RowGrid)
#print(ColGrid)
#print(Grid)

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row]
		TempColGrid = ColGrid
		for pointer in TempRow:
			TempCol = TempRow
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = TempColGrid[pointer]
#				print('pair is', pair)
#				print('row equal', row)
#				print('ObjCol equal', ObjCol)
#				print('TempColGrid[pointer] is', TempColGrid[pointer])
				if row in ObjCol:
					ObjCol.remove(row)
				for obj in ObjCol:
					val = Grid[(obj, pointer)]- dif 
					if (val < 0):
						print("No")
						exit()
					if ((obj, pair) in Grid):
						if (val != Grid[(obj, pair)]):
							print("No");
							exit()
					else:
						Grid[(obj, pair)] = val
						RowGrid[obj].append(pair)
						ColGrid[pair].append(obj)
						fresh = 1
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# D-Grid and Integers

from collections import defaultdict

def ReadInput():
	return [int(i) for i in input().split(" ")]

(R, C) = ReadInput()
N = int(input())
RowIdx = set()
ColIdx = set()
Grid = defaultdict(list)
RowGrid = defaultdict(list)
ColGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = ReadInput()
	RowGrid[r].append(c)
	ColGrid[c].append(r)
	Grid[(r, c)] = a
	RowIdx.add(r)
	ColIdx.add(c)	
print(RowIdx)
print(RowGrid)
print(ColGrid)
print(Grid)

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row]
		TempColGrid = ColGrid
		for pointer in TempRow:
			TempCol = TempRow
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = TempColGrid[pointer]
				print('pair is', pair)
				print('row equal', row)
				print('ObjCol equal', ObjCol)
				print('TempColGrid[pointer] is', TempColGrid[pointer])
				if row in ObjCol:
					ObjCol.remove(row)
				for obj in ObjCol:
					val = Grid[(obj, pointer)]- dif 
					if (val < 0):
						print("No")
						exit()
					if ((obj, pair) in Grid):
						if (val != Grid[(obj, pair)]):
							print("No");
							exit()
					else:
						Grid[(obj, pair)] = val
						RowGrid[obj].append(pair)
						ColGrid[pair].append(obj)
						fresh = 1
print("Yes")

Submission status: Wrong Answer

Solution code:
import numpy as np

R, C = map(int, raw_input().split())
N = int(raw_input())
rca_list = []




for i in range(N):
    rca_list.append(map(int, raw_input().split()))
    
r_vec = np.zeros(R)
r_vec_2 = np.zeros(R)
c_vec = np.zeros(C)
c_vec_2 = np.zeros(C)

# ret
ret = "YES"


while len(rca_list) > 0 and ret == "YES":
    # first square
    r, c, a = rca_list.pop()

    r_vec[r-1] = a
    c_vec[c-1] = 0
    r_vec_2[r-1] = 1
    c_vec_2[c-1] = 1

    go_flg = "YES"
    while go_flg == "YES" and ret == "YES":
        go_flg = "NO"
        for i in range(len(rca_list)-1, 0, -1):
            r, c, a = rca_list[i]
            # filled
            if r_vec_2[r-1] + c_vec_2[c-1] == 2:
                rca_list.pop(i)
                go_flg = "YES"
                if c != r_vec[r-1] + c_vec[c-1]:
                    ret = "NO"
            elif r_vec_2[r-1] + c_vec_2[c-1] == 1:
                if r_vec_2[r-1] == 1:
                    c_vec_2[c-1] = 1
                    c_vec[c-1] = a - r_vec[r-1]
                    rca_list.pop(i)
                    go_flg = "YES"
                elif c_vec_2[c-1] == 1:
                    r_vec_2[r-1] = 1
                    r_vec[r-1] = a - c_vec[c-1]
                    rca_list.pop(i)
                    go_flg = "YES"
            else:
                pass
            
if ret == "YES" and min(r_vec) + min(c_vec) >= 0:
    print "YES"
else:
    print "NO"

Submission status: Wrong Answer

Solution code:
import numpy as np

R, C = map(int, raw_input().split())
N = int(raw_input())
rca_list = []




for i in range(N):
    rca_list.append(map(int, raw_input().split()))
    
r_vec = np.zeros(R)
r_vec_2 = np.zeros(R)
c_vec = np.zeros(C)
c_vec_2 = np.zeros(C)

# ret
ret = "YES"


while len(rca_list) > 0 and ret == "YES":
    # first square
    r, c, a = rca_list.pop()

    r_vec[r-1] = a
    c_vec[c-1] = 0
    r_vec_2[r-1] = 1
    c_vec_2[c-1] = 1

    go_flg = "YES"
    while go_flg == "YES" and ret == "YES":
        go_flg = "NO"
        for i in range(len(rca_list)-1, 0, -1):
            r, c, a = rca_list[i]
            # filled
            if r_vec_2[r-1] + c_vec_2[c-1] == 2:
                rca_list.pop(i)
                go_flg = "YES"
                if c != r_vec[r-1] + c_vec[c-1]:
                    ret = "NO"
            elif r_vec_2[r-1] + c_vec_2[c-1] == 1:
                if r_vec_2[r-1] == 1:
                    c_vec_2[c-1] = 1
                    c_vec[c-1] = a - r_vec[r-1]
                    rca_list.pop(i)
                    go_flg = "YES"
                elif c_vec_2[c-1] == 1:
                    r_vec_2[r-1] = 1
                    r_vec[r-1] = a - c_vec[c-1]
                    rca_list.pop(i)
                    go_flg = "YES"
            else:
                pass
print ret

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)

class Edge:
	def __init__(self, v1, v2, w):
		self.v1 = v1
		self.v2 = v2
		self.w = w
	def __repr__(self):
		return 'Edges({},{},{})'.format(self.v1, self.v2, self.w)

def dfs(edges, v, visited, i, m, r):
	m[0 if i<r else 1] = min(m[0 if i<r else 1], v[i])
	for edge in edges[i]:
		if visited[edge.v2]:
			if (v[i] + v[edge.v2]) != edge.w:
				return False
			continue
		visited[edge.v2] = True
		v[edge.v2] = edge.w - v[i]
		if not dfs(edges, v, visited, edge.v2, m, r):
			return False
	return True

r, c = map(int, input().split())
edges = [list() for _ in range(r + c)]
v = [0] * (r + c)
visited = [False] * (r + c)
n = int(input())
for _ in range(n):
	ri, ci, ai = map(int, input().split())
	ri, ci = ri-1, ci-1
	edges[ri].append(Edge(ri, r+ci, ai))
	edges[r+ci].append(Edge(r+ci, ri, ai))

m = [10**10, 10**10]

if dfs(edges, v, visited, 0, m, r) and 0 <= sum(m):
	print('Yes')
else:
	print('No')

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)

class Edge:
	def __init__(self, v1, v2, w):
		self.v1 = v1
		self.v2 = v2
		self.w = w
	def __repr__(self):
		return 'Edges({},{},{})'.format(self.v1, self.v2, self.w)

def dfs(edges, v, visited, i, m, r):
	m[0 if i<r else 1] = min(m[0 if i<r else 1], v[i])
	for edge in edges[i]:
		if visited[edge.v2]:
			if (v[i] + v[edge.v2]) != edge.w:
				return False
			continue
		visited[edge.v2] = True
		v[edge.v2] = edge.w - v[i]
		if not dfs(edges, v, visited, edge.v2, m, r):
			return False
	return True

r, c = map(int, input().split())
edges = [list() for _ in range(r + c)]
v = [0] * (r + c)
visited = [False] * (r + c)
n = int(input())
for _ in range(n):
	ri, ci, ai = map(int, input().split())
	ri, ci = ri-1, ci-1
	edges[ri].append(Edge(ri, r+ci, ai))
	edges[r+ci].append(Edge(r+ci, ri, ai))

m = [10**6, 10**6]

if dfs(edges, v, visited, 0, m, r) and 0 <= sum(m):
	print('Yes')
else:
	print('No')

Submission status: Wrong Answer

Solution code:
class Edge:
	def __init__(self, v1, v2, w):
		self.v1 = v1
		self.v2 = v2
		self.w = w
	def __repr__(self):
		return 'Edges({},{},{})'.format(self.v1, self.v2, self.w)

def dfs(edges, v, visited, i, m, r):
	m[0 if i<r else 1] = min(m[0 if i<r else 1], v[i])
	for edge in edges[i]:
		if visited[edge.v2]:
			if (v[i] + v[edge.v2]) != edge.w:
				return False
			continue
		visited[edge.v2] = True
		v[edge.v2] = edge.w - v[i]
		if not dfs(edges, v, visited, edge.v2, m, r):
			return False
	return True

r, c = map(int, input().split())
edges = [list() for _ in range(r + c)]
v = [0] * (r + c)
visited = [False] * (r + c)
n = int(input())
for _ in range(n):
	ri, ci, ai = map(int, input().split())
	ri, ci = ri-1, ci-1
	edges[ri].append(Edge(ri, r+ci, ai))
	edges[r+ci].append(Edge(r+ci, ri, ai))

m = [10**6, 10**6]

if dfs(edges, v, visited, 0, m, r) and 0 <= sum(m):
	print('Yes')
else:
	print('No')

Submission status: Wrong Answer

Solution code:
print "No"

Submission status: Wrong Answer

Solution code:
from sys import stdin
from itertools import repeat
def main():
    r, c = map(int, stdin.readline().split())
    n = int(stdin.readline())
    a = map(int, stdin.read().split(), repeat(10, 3 * n))
    rs = [[] for i in xrange(c)]
    cs = [[] for i in xrange(r)]
    for i in xrange(n):
        a[i*3] -= 1
        y = a[i*3]
        a[i*3+1] -= 1
        x = a[i*3+1]
        rs[x].append((y, a[i*3+2]))
        cs[y].append((x, a[i*3+2]))
    v = [None] * c
    rd = [None] * r
    st = []
    pu = st.append
    po = st.pop
    for i in xrange(c):
        if v[i] is not None:
            continue
        if not rs[i]:
            continue
        mnc = v[i] = rs[i][0][1]
        pu((rs[i][0][0], rs[i][0][1], i, 0))
        mnr = 0
        while st:
            y, base, x, dr = po()
            for nx, val in cs[y]:
                tmp = val - dr
                if v[nx] is None:
                    v[nx] = tmp
                    if mnc > tmp:
                           mnc = tmp
                    for ny, nval in rs[nx]:
                        if not rd[ny]:
                            rd[ny] = 1
                            if 0 > nval - tmp < -mnr:
                                mnr = tmp - nval
                            pu((ny, nval, nx, nval - tmp))
                elif v[nx] != tmp:
                    print "No"
                    return
        if mnc < mnr:
            print "No"
            return
    print "Yes"
main()

Submission status: Wrong Answer

Solution code:
print('Yes')

Submission status: Wrong Answer

Solution code:
import math
R, C = map(int, input().split())
N = int(input())

board = [[float("inf") for i in range(C+2)]for j in range(R+2)]

dx = [-1, 0, 1, 1, 1, 0,-1,-1]
dy = [-1,-1,-1, 0, 1, 1, 1, 0]

def check(row, col, value):
    if math.isinf(value) or math.isnan(value):
        return
    if value < 0:
        print("No")
        exit()

    if row == 0 or row == R+1 or col == 0 or col == C+1:
        return

    if math.isinf(board[row][col]):
        # print(row, col, value)
        board[row][col] = value
        # print(board)
    else:
        if board[row][col] == value:
            return
        else:
            # print(row, col, value)
            # print(board)
            print("No")
            exit()

    for i in range(8):
        if i%2 == 0:
            check(row + dy[i], col + dx[i], - board[row][col] + board[row+dy[i]][col] + board[row][col+dx[i]])
        else:
            check(row + dy[i], col + dx[i], + board[row][col] + board[row+dy[(i+1)%8]][col+dx[(i+1)%8]] - board[row+dy[(i+2)%8]][col+dx[(i+2)%8]])
            check(row + dy[i], col + dx[i], + board[row][col] + board[row+dy[(i-1)%8]][col+dx[(i-1)%8]] - board[row+dy[(i-2)%8]][col+dx[(i-2)%8]])

for i in range(N):
    r, c, a = map(int, input().split())
    check(r, c, a)

print("YES")

Submission status: Wrong Answer

Solution code:
import math
R, C = map(int, input().split())
N = int(input())

board = [[float("inf") for i in range(C+2)]for j in range(R+2)]

dx = [-1, 0, 1, 1, 1, 0,-1,-1]
dy = [-1,-1,-1, 0, 1, 1, 1, 0]

def check(row, col, value):
    if math.isinf(value) or math.isnan(value):
        return
    if row == 0 or row == R+1 or col == 0 or col == C+1:
        return

    if math.isinf(board[row][col]):
        board[row][col] = value
    else:
        if board[row][col] == value:
            return
        else:
            print("No")
            exit()

    for i in range(8):
        if i%2 == 0:
            check(row + dy[i], col + dx[i], - board[row][col] + board[row+dy[i]][col] - board[row][col+dx[i]])
        else:
            check(row + dy[i], col + dx[i], + board[row][col] - board[row+dy[(i+1)%8]][col+dx[(i+1)%8]] + board[row+dy[(i+2)%8]][col+dx[(i+2)%8]])
            check(row + dy[i], col + dx[i], + board[row][col] - board[row+dy[(i-1)%8]][col+dx[(i-1)%8]] + board[row+dy[(i-2)%8]][col+dx[(i-2)%8]])

for i in range(N):
    r, c, a = map(int, input().split())
    check(r, c, a)

print("YES")

Submission status: Wrong Answer

Solution code:
"""難しいすぎるよぅ..."""

def solve():
    R, C = list(map(int, input().split()))
    N = int(input())
    row = [[] for _ in range(R)]
    field = {}
    for _ in range(N):
        r, c, a = list(map(int, input().split()))
        r, c = r - 1, c - 1
        row[r].append((c, a))
        field[(r, c)] = a
    row = [sorted(r) for r in row]
    for rn, r in enumerate(row):
        for i, e1 in enumerate(r):
            for e2 in r[i+1:]:
                n = e2[0] - e1[0]
                print(r, e1, e2, n)
                if n > C:
                    break
                a = field.get((rn+n, e1[0]), None)
                b = field.get((rn+n, e2[0]), None)
                if a is None and b is None:
                    continue
                if a is None:
                    if e1[1] + b - e2[1] < 0:
                        return False
                elif b is None:
                    if e2[1] + a - e1[1] < 0:
                        return False
                else:
                    if e1[1] + b == e2[1] + a:
                        return False
    return True

print("Yes" if solve() else "No")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from copy import deepcopy

def check(a):
    a = list(a)
    if -1 in a:
        i = a.index(-1)
        a[i] = 0
        if i in (0, 3):
            return(a[0]+a[3]) <= (a[1]+a[2])
        else:
            return (a[0]+a[3]) >= (a[1]+a[2])
    else:
        return a[0]+a[3] == a[1]+a[2]
    return False

r, c = map(int, input().split())
n = int(input())
rc = defaultdict(lambda: defaultdict(lambda: -1))
for i in range(n):
    ri, ci, ai = map(int, input().split())
    rc[ri][ci] = ai
a = []
for i in list(rc):
    for j in list(rc[i]):
        if (rc[i][j] == -1):
            continue
        if (rc[i-1][j-1], rc[i][j-1], rc[i-1][j]).count(-1) <= 1:
            a.append((rc[i-1][j-1], rc[i][j-1], rc[i-1][j], rc[i][j]))
        if (rc[i-1][j], rc[i-1][j+1], rc[i][j+1]).count(-1) <= 1:
            a.append((rc[i-1][j], rc[i-1][j+1], rc[i][j], rc[i][j+1]))
        if (rc[i][j-1], rc[i+1][j-1], rc[i+1][j]).count(-1) <= 1:
            a.append((rc[i][j-1], rc[i][j], rc[i+1][j-1], rc[i+1][j]))
        if (rc[i][j+1], rc[i+1][j], rc[i+1][j+1]).count(-1) <= 1:
            a.append((rc[i][j], rc[i][j+1], rc[i+1][j], rc[i+1][j+1]))
b = []
sb = []
for aa in a:
    if sorted(aa) not in sb:
        b.append(aa)
        sb.append(sorted(aa))

flag = True
for bb in b:
    if not check(bb):
        flag = False

if flag:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
R, C = map(int, input().split())
N = int(input())
n = 0
Is = []
while n < N:
    Is.append(list(map(int, input().split())))
    n += 1

# matrix = [None] * (R * C)

# for i in Is:
#     r, c, a = i
#     serial = (r - 1) * C + c
#     matrix[serial] = [a]

# for row in range(1, R):
#     nums = [i for i in matrix[row * C: (row + 1) * C - 1] if i is not None]
#     for compare_row in range(row):
#         compare_nums = [i for i in matrix[compare_row * C: (compare_row + 1) * C - 1] if i is not None]


print('Yes')

Submission status: Wrong Answer

Solution code:
def work():
    r, c = map(int, raw_input().split())
    n = int(raw_input())
    table = [[None] * c for _ in xrange(r)]
    diff = [None] * (r-1)
    nums = [None] * n
    for i in xrange(n):
        x, y, z = map(int, raw_input().split())
        nums[i] = (x, y, z)
    nums.sort()
    for i in xrange(n):
        x, y, z = nums[i]
        table[x-1][y-1] = z
        if x < r and table[x][y-1] is not None:
            if diff[x-1] is None:
                diff[x-1] = table[x][y-1] - table[x-1][y-1]
            elif table[x][y-1] - table[x-1][y-1] != diff[x-1]:
                return 'No'
        if x > 1 and table[x-2][y-1] is not None:
            if diff[x-2] is None:
                diff[x-2] = table[x-1][y-1] - table[x-2][y-1]
            elif table[x-1][y-1] - table[x-2][y-1] != diff[x-2]:
                return 'No'
    # for ii in xrange(r - 1):
    #     if diff[ii] is None:
    #         continue
    #     for jj in xrange(c):
    #         if table[ii][jj] and table[ii+1][jj]:
    #             if table[ii+1][jj] - table[ii][jj] != diff[ii]:
    #                 return 'No'
    #         elif table[ii][jj]:
    #             if table[ii][jj] + diff[ii] < 0:
    #                 return 'No'
    #         elif table[ii+1][jj]:
    #             if table[ii+1][jj] - diff[ii] < 0:
    #                 return 'No'
    return 'Yes'


print work()