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: Time Limit Exceeded

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

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")
				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")
		exit()

print("Yes")

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys
import copy
sys.setrecursionlimit(10**6)

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

(R, C) = readInput()
N = int(input())
rowIdx = set() 
cover = set()
grid = defaultdict(lambda:None)
rowGrid = defaultdict(set)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].add(c)
	grid[(r, c)] = a 
	rowIdx.add(r)

pairIdx = copy.copy(rowIdx)	
for i in rowIdx:
	tempRow = rowGrid[i]
	tempRow.difference_update(cover)
	if (len(tempRow) is 0):
		continue
	pairIdx.remove(i)
	for j in pairIdx:
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] is not None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
				break
		if (mark is 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP is None and anchor < diff):
				print('No')
				exit()
			elif (anchorP is not None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP is None and anchor < -diff):
				print('No')
				exit()
	cover &= tempRow
	if (len(cover) is C):
		break
print('Yes')

Submission status: Time Limit Exceeded

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")
				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")
		exit()
		
print("Yes")

Submission status: Time Limit Exceeded

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

from collections import defaultdict
import copy

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

(R, C) = readInput()
N = int(input())
rowIdx = set() 
cover = set()
grid = defaultdict(lambda:None)
rowGrid = defaultdict(set)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].add(c)
	grid[(r, c)] = a 
	rowIdx.add(r)

pairIdx = copy.copy(rowIdx)	
for i in rowIdx:
	tempRow = rowGrid[i]
	tempRow.difference_update(cover)
	if (len(tempRow) is 0):
		continue
	pairIdx.remove(i)
	for j in pairIdx:
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] is not None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
				break
		if (mark is 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP is None and anchor < diff):
				print('No')
				exit()
			elif (anchorP is not None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP is None and anchor < -diff):
				print('No')
				exit()
	cover &= tempRow
	if (len(cover) is C):
		break
print('Yes')

Submission status: Time Limit Exceeded

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

from collections import defaultdict
import copy

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

(R, C) = readInput()
N = int(input())
rowIdx = set() 
cover = set()
grid = defaultdict(lambda:None)
rowGrid = defaultdict(set)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].add(c)
	grid[(r, c)] = a 
	rowIdx.add(r)

pairIdx = copy.copy(rowIdx)	
for i in rowIdx:
	tempRow = rowGrid[i]
	tempRow.difference_update(cover)
	if (len(tempRow) is 0):
		continue
	pairIdx.remove(i)
	for j in pairIdx:
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] != None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
		if (mark is 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP is None and anchor < diff):
				print('No')
				exit()
			elif (anchorP is not None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP is None and anchor < -diff):
				print('No')
				exit()
	cover &= tempRow
	if (len(cover) is C):
		break
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

(R, C) = readInput()
N = int(input())
rowIdx = set() 
grid = defaultdict(lambda:None)
rowGrid = defaultdict(set)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].add(c)
	grid[(r, c)] = a 
	rowIdx.add(r)

pairIdx = rowIdx.copy()
for i in rowIdx:
	pairIdx.remove(i)
	for j in pairIdx:
		tempRow = rowGrid[i]
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] != None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
		if (mark is 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP is None and anchor < diff):
				print('No')
				exit()
			elif (anchorP is not None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP is None and anchor < -diff):
				print('No')
				exit()
print('Yes')

Submission status: Time Limit Exceeded

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

from collections import defaultdict
import copy

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

(R, C) = readInput()
N = int(input())
rowIdx = list() 
colIdx = list()
grid = defaultdict(lambda:None)
rowGrid = 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)

pairIdx = copy.copy(rowIdx)	
for i in rowIdx:
	pairIdx.remove(i)
	for j in pairIdx:
		tempRow = rowGrid[i]
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] != None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
		if (mark  == 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP == None and anchor < diff):
				print('No')
				exit()
			elif (anchorP != None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP == None and anchor < -diff):
				print('No')
				exit()
print('Yes')

Submission status: Time Limit Exceeded

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() 
colIdx = list()
grid = defaultdict(lambda:None)
rowGrid = 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)

pairIdx = rowIdx.copy()	
for i in rowIdx:
	pairIdx.remove(i)
	for j in pairIdx:
		tempRow = rowGrid[i]
		tempPair = rowGrid[j]
		mark = 1
		for k in tempRow:
			if (grid[(j, k)] != None):
				diff = grid[(i, k)] - grid[(j, k)]
				mark = 0 
		if (mark  == 1):
			continue
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP == None and anchor < diff):
				print('No')
				exit()
			elif (anchorP != None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP == None and anchor < -diff):
				print('No')
				exit()
print('Yes')

Submission status: Time Limit Exceeded

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() 
colIdx = list()
grid = defaultdict(lambda:None)
rowGrid = defaultdict(list)
colGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].append(c)
	colGrid[c].append(r)
	grid[(r, c)] = a 
	rowIdx.append(r)
	colIdx.append(c)

pairIdx = rowIdx.copy()	
for i in rowIdx:
	pairIdx.remove(i)
	for j in pairIdx:
		tempRow = set(rowGrid[i])
		tempPair = set(rowGrid[j])
		intersect = tempRow.intersection(tempPair)
		if (len(intersect) == 0):
			continue
		col = list(intersect)[0]
		diff = grid[(i, col)] - grid[(j, col)] 
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP == None and anchor < diff):
				print('No')
				exit()
			elif (anchorP != None and anchor - anchorP != diff):
				print('No')
				exit()
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP == None and anchor < -diff):
				print('No')
				exit()
print('Yes')

Submission status: Time Limit Exceeded

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() 
colIdx = list()
grid = defaultdict(lambda:None)
rowGrid = defaultdict(list)
colGrid = defaultdict(list)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].append(c)
	colGrid[c].append(r)
	grid[(r, c)] = a 
	rowIdx.append(r)
	colIdx.append(c)

pairIdx = rowIdx.copy()	
for i in rowIdx:
	pairIdx.remove(i)
	for j in pairIdx:
		tempRow = set(rowGrid[i])
		tempPair = set(rowGrid[j])
		intersect = tempRow.intersection(tempPair)
		if (len(intersect) == 0):
			continue
		col = list(intersect)[0]
		diff = grid[(i, col)] - grid[(j, col)] 
		for m in tempRow:
			anchor = grid[(i, m)]
			anchorP = grid[(j, m)]
			if (anchorP == None and anchor < diff):
				print('No')
				exit()
			elif (anchorP != None and anchor - anchorP != diff):
				print('No')
				exit()
		tempPair.difference_update(tempRow)
		for n in tempPair:
			anchor = grid[(j, n)]
			anchorP = grid[(i, n)]
			if (anchorP == None and anchor < -diff):
				print('No')
				exit()
print('Yes')

Submission status: Time Limit Exceeded

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 = set()
grid = defaultdict(int)
coverGrid = defaultdict(set)
rowGrid = defaultdict(set)
colGrid = defaultdict(set)
for i in range(N):
	(r, c, a) = readInput()
	r -= 1
	c -= 1
	rowGrid[r].add(c)
	colGrid[c].add(r)
	grid[(r, c)] = a 
	rowIdx.add(r)

for rowNum in rowIdx:
	row = rowGrid[rowNum]
	if (len(row) == 1):
		continue
	coverRow = coverGrid[rowNum]
	if (row.issubset(coverRow)):
		continue
	elif (len(coverRow) == 0):
		tempRow = row
	else:
		intersect = coverRow.intersection(row)
		dif = coverRow.difference(row)
		dif.add(intersect.pop()) 
		tempRow = dif
	tempRowIdx = rowIdx.copy()	
	tempRowIdx.remove(rowNum)
	for pairRowIdx in tempRowIdx:
		pairRow = rowGrid[pairRowIdx] 
		intersect = tempRow.intersection(pairRow)
		dif = tempRow.difference(pairRow)
		if (len(intersect) == 0):
			continue
		listTempRow = list(tempRow)
		listPairRow = list(pairRow)
		i = list(intersect)[0] 
		q = grid[(rowNum,i)] - grid[(pairRowIdx,i)]
		for pointer in intersect:
			tempQ = grid[(rowNum,pointer)] - grid[(pairRowIdx,pointer)]
			if (q != tempQ):
				print("No")
				exit()
		for pointer in dif:
			if (grid[(rowNum,pointer)]- q < 0): 
				print("No")
				exit()
	coverGrid[rowNum] |= tempRow
print("Yes")

Submission status: Time Limit Exceeded

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)	

for row in RowIdx:
	if (len(RowGrid[row]) == 1):
		continue
	TempRow = RowGrid[row]
	for pointer in TempRow:
		TempCol = TempRow.copy()
		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)
print("Yes")

Submission status: Time Limit Exceeded

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)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row]
		for pointer in TempRow:
			TempCol = TempRow.copy()
			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: Time Limit Exceeded

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 a != 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: Time Limit Exceeded

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==1]) + min(c_vec[c_vec==1]) < 0:
        ret = "NO"
    
print ret

Submission status: Time Limit Exceeded

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)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row].copy()
		TempColGrid = ColGrid.copy()
		for pointer in TempRow:
			TempCol = TempRow.copy()
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = TempColGrid[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: Time Limit Exceeded

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)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row].copy()
		TempColGrid = ColGrid.copy()
		for pointer in TempRow:
			TempCol = TempRow.copy()
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = TempColGrid[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:
						Grid[(obj, pair)] = val
						RowGrid[obj].append(pair)
						ColGrid[pair].append(obj)
						fresh = 1
print("Yes")

Submission status: Time Limit Exceeded

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)	

fresh = 1
while(fresh == 1):
	fresh = 0
	for row in RowIdx:
		if (len(RowGrid[row]) == 1):
			continue
		TempRow = RowGrid[row].copy()
		TempColGrid = ColGrid.copy()
		for pointer in TempRow:
			TempCol = TempRow.copy()
			TempCol.remove(pointer)
			for pair in TempCol:
				dif = Grid[(row, pointer)] - Grid[(row, pair)]
				ObjCol = TempColGrid[pointer].copy()
				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: Time Limit Exceeded

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
                elif v[nx] != tmp:
                    print "No"
                    return
                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))
        if mnc < mnr:
            print "No"
            return
    print "Yes"
main()

Submission status: Time Limit Exceeded

Solution code:
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

setrecursionlimit(10000)

(R, C) = reads()
N = read()

d = defaultdict(list)
V = set()

for _ in range(N):
  (r, c, a) = reads()
  d["R", r-1].append((("C", c-1), a))
  d["C", c-1].append((("R", r-1), a))
  V.add(("R", r-1))
  V.add(("C", c-1))

def walk(v):
  for (w, a) in d[v]:
    wcol = a - col[v]
    if w in col:
      if col[w] != wcol:
        print("No"); exit()
    else:
      col[w] = wcol
      walk(w)

while len(V) > 0:
  col = dict()
  v = V.pop()
  col[v] = 0
  walk(v)
  rcol = min(a for (v, a) in col.items() if v[0] == "R")
  ccol = min(a for (v, a) in col.items() if v[0] == "C")
  if rcol + ccol < 0:
    print("No"); exit()

print("Yes")

Submission status: Time Limit Exceeded

Solution code:
import sys 

    
h,w = map(int,sys.stdin.readline().split())
N = int(sys.stdin.readline())
grids = [[None for x in range(w+2)] for y in range (h+2)]

def fill2x2grid(r,c):
        if grids[r][c]== None:
                return writegrid(r,c,grids[r+1][c]+grids[r][c+1]-grids[r+1][c+1])
        if grids[r+1][c]== None:
                return writegrid(r+1,c,grids[r][c]+grids[r+1][c+1]-grids[r][c+1])
        if grids[r][c+1]== None:
                return writegrid(r,c+1,grids[r][c]+grids[r+1][c+1]-grids[r+1][c])
        if grids[r+1][c+1]== None:
                return writegrid(r+1,c+1,grids[r+1][c]+grids[r][c+1]-grids[r][c])
def valid2x2(r,c):
        if r<0 or c<0 or r> h+1 or c> w+1:
                return True
        gg=[grids[r][c],grids[r+1][c+1],grids[r+1][c],grids[r][c+1]]
        ggc = gg.count(None)
        if ggc == 0:
                return gg[0]+gg[1] == gg[2]+gg[3]
        if ggc == 1:
                return fill2x2grid(r,c)
        return True
    
def valid3x3(r,c):
        return valid2x2(r,c) and valid2x2(r+1,c) and valid2x2(r,c+1) and valid2x2(r+1,c+1)
def writegrid(r,c,a):
        if a < 0:
                print "No"                                                                                                                                                                                                            
                sys.exit(0)
        if grids[r][c] != None: 
                if grids[r][c] == a:
                        pass
                else:
                        print "No"
                        sys.exit(0)
        grids[r][c] = a 
        if not valid3x3(r-1,c-1):
                print "No"
                sys.exit(0)
        return True
    
for i in range(N):
        r,c,a = map(int, sys.stdin.readline().split())
        if not writegrid(r,c,a):
                print "No"
                sys.exit(0)
print "Yes"

Submission status: Time Limit Exceeded

Solution code:
def check_squares(grid, coord, isFilled):
    rows, cols = len(grid), len(grid[0])
    r, c = coord[0], coord[1]
    sums = []

    if r - 1 >= 0 and c - 1 >= 0: # check upper left square
        if isFilled and (grid[r][c - 1] + grid[r - 1][c] != grid[r][c] + grid[r - 1][c - 1]):
            raise ValueError('not filled correctly')

        elif not isFilled and grid[r][c - 1] is not None and grid[r - 1][c] is not None and grid[r - 1][c - 1] is not None:
            sums.append((grid[r][c - 1] + grid[r - 1][c]) - grid[r - 1][c - 1])

    if r - 1 >= 0 and c + 1 < cols: # check upper right square
        if isFilled and (grid[r - 1][c] + grid[r][c + 1] != grid[r][c] + grid[r - 1][c + 1]):
            raise ValueError('not filled correctly')

        elif not isFilled and grid[r - 1][c] is not None and grid[r - 1][c + 1] is not None and grid[r][c + 1] is not None:
            sums.append((grid[r - 1][c] + grid[r][c + 1]) - grid[r - 1][c + 1])

    if r + 1 < rows and c - 1 >= 0: # check lower left
        if isFilled and (grid[r][c] + grid[r + 1][c - 1] != grid[r][c - 1] + grid[r + 1][c]):
            raise ValueError('not filled correctly')

        elif not isFilled and grid[r][c - 1] is not None and grid[r + 1][c] is not None and grid[r + 1][c - 1] is not None:
            sums.append((grid[r][c - 1] + grid[r + 1][c]) - grid[r + 1][c - 1])

    if r + 1 < rows and c + 1 < cols: # check lower right
        if isFilled and (grid[r + 1][c + 1] + grid[r][c] != grid[r][c + 1] + grid[r + 1][c]):
            raise ValueError('not filled correctly')

        elif not isFilled and grid[r][c + 1] is not None and grid[r + 1][c] is not None and grid[r + 1][c + 1] is not None:
            sums.append((grid[r + 1][c] + grid[r][c + 1]) - grid[r + 1][c + 1])

    if len(sums) > 1 and len(set(sums)) > 1:
        raise ValueError('Square cannot be filled in')
    elif len(sums) == 1:
        if sums[0] < 0:
            raise ValueError('Value would have to be negative')
        return sums[0]
    else:
        return None

r, c = map(int, raw_input().split())
n = int(raw_input())
grid = [ [None for i in range(c)] for j in range(r) ]

for i in range(n):
    line = map(int, raw_input().split())
    grid[line[0] - 1][line[1] - 1] = line[2]


filled = (n == r * c)
for i in range(r):
    for j in range(c):
        if grid[i][j] is None or filled:
            try:
                result = check_squares(grid, (i, j), filled)
                if not filled:
                    grid[i][j] = result
            except ValueError:
                print 'No'
                exit()

print 'Yes'