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.

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w = list(map(int, input().split()))
n = int(input())
from collections import defaultdict
mind = [10**15] * h
dw = defaultdict(list)
for i in range(n):
    r,c,a = map(int, input().split())
    r -= 1
    c -= 1
    mind[r] = min(mind[r], a)
    dw[c].append((a,r))

es = [[] for _ in range(h)]
def main():
    ans = True
    for c in range(w):
        if len(dw[c])<=1:
            continue
        dw[c].sort()
        tmp = 0
        for i in range(len(dw[c])-1):
            u = dw[c][i][1]
            v = dw[c][i+1][1]
            val = dw[c][i+1][0] - dw[c][i][0]
            es[u].append((val, v))
            es[v].append((-val, u))
            tmp += val
            if mind[v]<tmp:
                return False


    vals = [None]*h
    for start in range(h):
        if vals[start] is not None:
            continue
        q = [start]
        vals[start] = 0
        l = [(0, mind[start])]
        while q:
            u = q.pop()
            for d,v in es[u]:
                if vals[v] is None:
                    vals[v] = vals[u] + d
                    l.append((vals[v], mind[v]))
                    q.append(v)
                elif vals[v]!=vals[u]+d:
                    return False
        l.sort()
        for i in range(len(l)):
            if l[i][1]<l[i][0]-l[0][0]:
                return False




    return True
ans = main()
if ans:
    print("Yes")
else:
    print("No")

Solution (Python):
import sys
readline = sys.stdin.readline
class UFP():
    def __init__(self, num):
        self.par = [-1]*num
        self.dist = [0]*num
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            res = 0
            xo = x
            while self.par[x] >= 0:
                res += self.dist[x]
                x = self.par[x]
            self.dist[xo] = res
            self.par[xo] = x
            return x
    
    def union(self, x, y, d):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            if self.par[rx] > self.par[ry]:
                rx, ry = ry, rx
                x, y = y, x
                d = -d
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
            self.dist[ry] = d + self.dist[x] - self.dist[y]
            return True
        else:
            if d + self.dist[x] - self.dist[y]:
                return False
            return True           
    
INF = 3*10**9
def check():
    H, W = map(int, readline().split())
    N = int(readline())
    Hm = [INF]*H
    Wm = [INF]*W
    HP = [[] for _ in range(H)]
    WP = [[] for _ in range(W)]
    for _ in range(N):
        h, w, a = map(int, readline().split())
        h -= 1
        w -= 1
        Hm[h] = min(Hm[h], a)
        Wm[w] = min(Wm[w], a)
        HP[h].append((w, a))
        WP[w].append((h, a))
        
    Th = UFP(H)
    Tw = UFP(W)
    for h in range(H):
        L = len(HP[h]) 
        if L > 1:
            HP[h].sort()
            for i in range(L-1):
                wp, ap = HP[h][i]
                wn, an = HP[h][i+1]
                if not Tw.union(wp, wn, an-ap):
                    return False
    for w in range(W):
        L = len(WP[w]) 
        if L > 1:
            WP[w].sort()
            for i in range(L-1):
                hp, ap = WP[w][i]
                hn, an = WP[w][i+1]
                if not Th.union(hp, hn, an-ap):
                    return False
    
    cmh = [INF]*H
    for h in range(H):
        rh = Th.find(h)
        cmh[rh] = min(cmh[rh], Th.dist[h])
    cmw = [INF]*W
    for w in range(W):
        rw = Tw.find(w)
        cmw[rw] = min(cmw[rw], Tw.dist[w])
    
    for h in range(H):
        if Hm[h] - Th.dist[h] + cmh[Th.find(h)] < 0:
            return False
    for w in range(W):
        if Wm[w] - Tw.dist[w] + cmw[Tw.find(w)] < 0:
            return False
    return True

print('Yes' if check() else 'No')

Solution (Python):
import sys
input = sys.stdin.readline
R, C = map(int, input().split())
n = int(input())
G = [[] for _ in range(R+C)]
for _ in range(n):
  r, c, a = map(int, input().split())
  r -= 1
  c -= 1
  G[r].append((R+c, a))
  G[R+c].append((r, a))
D = [-1]*(R+C)
def dfs(v):
  rmin, cmin = float("inf"), float("inf")
  stack = [(v, 0)]
  while stack:
    nv, cost = stack.pop()
    D[nv] = cost
    if nv<R:
      rmin = min(rmin, cost)
    else:
      cmin = min(cmin, cost)
    for i, nc in G[nv]:
      if D[i] != -1:
        if D[nv]+D[i] != nc:
          return False
      else:
        stack.append((i, nc-D[nv]))
  return rmin+cmin >= 0

for i in range(R+C):
  if D[i] == -1:
    if not dfs(i):
      print("No")
      break
else:
  print("Yes")

Solution (Python):



class WeightedUnionFind:
    
    def __init__(self, n, SUM_UNITY=0):
        self.par = list(range(n))
        self.rank = [0] * n
        self.diff_weight = [SUM_UNITY] * n

    def root(self, x):
        p = self.par[x]
        if p == x:
            return x
        else:
            r = self.root(p)
            self.diff_weight[x] += self.diff_weight[p]
            self.par[x] = r
            return r

    def weight(self, x):
        self.root(x)
        return self.diff_weight[x]

    def same(self, x, y):
        return self.root(x) == self.root(y)

    def unite(self, x, y, w):
        if self.same(x, y):
            return self.diff(x, y) == w
        w += self.weight(x);  w -= self.weight(y)
        x, y = self.root(x), self.root(y)
        
        
        if self.rank[x] < self.rank[y]:
            x, y = y, x
            w = -w
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.par[y] = x
        self.diff_weight[y] = w
        return True

    def diff(self, x, y):
        return self.weight(y) - self.weight(x)

    def get_roots_weights(self):
        roots = []
        weights = []
        for x in range(len(self.par)):
            roots.append(self.root(x))
            weights.append(self.weight(x))
        return roots, weights

import sys
from operator import itemgetter
from itertools import groupby
from collections import defaultdict

def main():
    R, C = map(int, input().split())
    N = int(input())
    RCA = list(zip(*[iter(map(int, sys.stdin.read().split()))]*3))
    uf_r = WeightedUnionFind(R+1)
    uf_c = WeightedUnionFind(C+1)

    RCA.sort(key=itemgetter(0))
    for _, g in groupby(RCA, key=itemgetter(0)):
        _, c0, a0 = next(g)
        for _, c, a in g:
            if not uf_c.unite(c0, c, a-a0):
                print("No")
                exit()

    RCA.sort(key=itemgetter(1))
    for _, g in groupby(RCA, key=itemgetter(1)):
        r0, _, a0 = next(g)
        for r, _, a in g:
            if not uf_r.unite(r0, r, a-a0):
                print("No")
                exit()

    r_roots, r_weights = uf_r.get_roots_weights()
    c_roots, c_weights = uf_c.get_roots_weights()
    r_roots_inv = defaultdict(list)
    for i, r in enumerate(r_roots):
        r_roots_inv[r].append(i)
    c_roots_inv = defaultdict(list)
    for i, r in enumerate(c_roots):
        c_roots_inv[r].append(i)
    Closed_r = set()
    Closed_c = set()
    for r, c, a in RCA:
        root_r, root_c = r_roots[r], c_roots[c]
        if root_r in Closed_r:
            assert root_c in Closed_c
            continue
        Closed_r.add(root_r)
        Closed_c.add(root_c)
        mi = float("inf")
        for v in r_roots_inv[root_r]:
            mi = min(mi, r_weights[v])
        a += mi - r_weights[r]
        for v in c_roots_inv[root_c]:
            a_ = a + c_weights[v] - c_weights[c]
            if a_ < 0:
                print("No")
                exit()
    print("Yes")

main()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

R,C = map(int,input().split())
N = int(input())
RCA = [tuple(int(x) for x in input().split()) for _ in range(N)]


graph = [[] for _ in range(R+C)]
for r,c,a in RCA:
    graph[r-1].append((R+c-1,a))
    graph[R+c-1].append((r-1,a))

graph


wt_temp = [None] * (R+C)
wt = [None] * (R+C)
for x in range(R+C):
    if wt_temp[x] is not None:
        continue
    wt_temp[x] = 0
    min_wt_row = 0
    q = [x]
    while q:
        y = q.pop()
        for z,a in graph[y]:
            if wt_temp[z] is not None:
                continue
            wt_temp[z] = a - wt_temp[y]
            q.append(z)
            if z<R and min_wt_row > wt_temp[z]:
                min_wt_row = wt_temp[z]
    wt[x] = -min_wt_row
    q = [x]
    while q:
        y = q.pop()
        for z,a in graph[y]:
            if wt[z] is not None:
                continue
            wt[z] = a - wt[y]
            q.append(z)

bl = True
if any(x<0 for x in wt):
    bl = False
for r,c,a in RCA:
    if wt[r-1] + wt[R+c-1] != a:
        bl = False

answer = 'Yes' if bl else 'No'
print(answer)

Solution (Python):
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")

Solution (Python):



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

R, C = map(int, input().split())
N = int(input())
VectorSet = set()
Grid = defaultdict(list)
for i in range(N):
	r, c, a = map(int, input().split())
	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 VectorSet:
	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")

Solution (Python):




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

Solution (Python):




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

Solution (Python):
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")

Solution (Python):
from collections import deque
r, c = map(int, raw_input().split())
n = input()
P = [map(int, raw_input().split()) for i in xrange(n)]

d = {}
P.sort()
for i in xrange(1, n):
    r1, c1, a1 = P[i-1]
    r2, c2, a2 = P[i]
    if r1 == r2:
        d.setdefault((r1, c1), []).append(((r2, c2), a2-a1))
        d.setdefault((r2, c2), []).append(((r1, c1), a1-a2))
P.sort(key=lambda (r,c,a): (c,r))
for i in xrange(1, n):
    r1, c1, a1 = P[i-1]
    r2, c2, a2 = P[i]
    if c1 == c2:
        d.setdefault((r1, c1), []).append(((r2, c2), a2-a1))
        d.setdefault((r2, c2), []).append(((r1, c1), a1-a2))
m = {}
for i, (r0, c0, a0) in enumerate(P):
    m[r0, c0] = (a0, i)
used = [0]*n
for i in xrange(n):
    if not used[i]:
        r0, c0, base = P[i]

        used[i] = 1
        deq = deque()
        deq.append((r0, c0, base))
        rs = {r0: 0}
        cs = {c0: 0}

        while deq:
            r0, c0, now = deq.popleft()

            for (r1, c1), diff in d.get((r0, c0), []):
                a1, j = m[r1, c1]
                if r0 == r1:
                    if not used[j]:
                        cs[c1] = cs[c0] + diff
                        used[j] = 1
                        deq.append((r1, c1, now + diff))
                    else:
                        if cs[c0] + diff != cs[c1]:
                            print "No"
                            exit(0)
                else:
                    if not used[j]:
                        rs[r1] = rs[r0] + diff
                        used[j] = 1
                        deq.append((r1, c1, now + diff))
                    else:
                        if rs[r0] + diff != rs[r1]:
                            print "No"
                            exit(0)
        rmin = min(rs.values())
        cmin = min(cs.values())
        if rmin + cmin + base < 0:
            print "No"
            exit(0)
print "Yes"

Solution (Python):
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))

flag = True
for i in range(r + c):
	if visited[i]:
		continue
	m = [10**10, 10**10]
	if (not dfs(edges, v, visited, i, m, r)) or sum(m) < 0:
		flag = False
if flag:
	print('Yes')
else:
	print('No')

Solution (Python):
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(1000000)

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

d = defaultdict(list)
V = set()

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

def walk(v):
  V.discard(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:
  v = V.pop()
  col = dict()
  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")

Solution (Python):
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 = 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()