Problem:
 Score : 600 points    Problem Statement Kenkoooo found a simple connected graph.
The vertices are numbered 1 through n .
The i -th edge connects Vertex u_i and v_i , and has a fixed integer s_i .  Kenkoooo is trying to write a positive integer in each vertex so that the following condition is satisfied:   For every edge i , the sum of the positive integers written in Vertex u_i and v_i is equal to s_i .   Find the number of such ways to write positive integers in the vertices.      Constraints  2 \leq n \leq 10^5  1 \leq m \leq 10^5  1 \leq u_i < v_i \leq n  2 \leq s_i \leq 10^9  If i\neq j , then u_i \neq u_j or v_i \neq v_j .  The graph is connected.  All values in input are integers.         Input Input is given from Standard Input in the following format:  n  m  u_1  v_1  s_1  :  u_m  v_m  s_m       Output Print the number of ways to write positive integers in the vertices so that the condition is satisfied.        Sample Input 1 3 3
1 2 3
2 3 5
1 3 4      Sample Output 1 1  The condition will be satisfied if we write 1,2 and 3 in vertices 1,2 and 3 , respectively.
There is no other way to satisfy the condition, so the answer is 1 .       Sample Input 2 4 3
1 2 6
2 3 7
3 4 5      Sample Output 2 3  Let a,b,c and d be the numbers to write in vertices 1,2,3 and 4 , respectively.
There are three quadruples (a,b,c,d) that satisfy the condition:   (a,b,c,d)=(1,5,2,3)  (a,b,c,d)=(2,4,3,2)  (a,b,c,d)=(3,3,4,1)        Sample Input 3 8 7
1 2 1000000000
2 3 2
3 4 1000000000
4 5 2
5 6 1000000000
6 7 2
7 8 1000000000      Sample Output 3 0

Solution (Python):
from math import ceil,floor
N,M=map(int,input().split())
Graph=[[] for i in range(N)]
for i in range(M):
  a,b,s=map(int,input().split())
  Graph[a-1].append((b-1,s))
  Graph[b-1].append((a-1,s))
inf=float("inf")  
node=[(0,0) for i in range(N)]
visited=[False]*N
node[0],visited[0]=(1,0),True
L,R=1,inf
stack=[0]
while stack:
  n=stack.pop()
  x,y=node[n]
  visited[n]=True
  for i,s in Graph[n]:
    if visited[i]:
      continue
    p,q=node[i]
    stack.append(i)
    if p:
      if p+x==0:
        if y+q!=s:
          print(0)
          exit()
      elif (s-y-q)%(p+x) or (not L<=(s-y-q)/(p+x)<=R):
        print(0)
        exit()
      else:
        L=R=(s-y-q)//(p+x)
    else:
      p,q=-x,s-y
      if p>0:
        L=max(L,floor(-q/p)+1)
      else:
        R=min(R,ceil(-q/p)-1)
      if L>R:
        print(0)
        exit()
      node[i]=(-x,s-y)
print(R-L+1)

Solution (Python):
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**6) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n,m = li()

INF = float("inf")
graph = [[] for _ in range(n)]

for _ in range(m):
    u,v,s = li()
    u -= 1
    v -= 1
    graph[u].append((v, s))
    graph[v].append((u, s))
    
a = [INF]*n
b = [INF]*n
a[0] = 1
b[0] = 0

def dfs(graph, cur, x):
    for nex, edge in graph[cur]:
        if a[nex] == INF:
            a[nex] = -a[cur]
            b[nex] = edge - b[cur]
            
            res, x = dfs(graph, nex, x)
            
            if not res:
                return False, None
            
        else:
            atemp = -a[cur]
            btemp = edge - b[cur]
            
            if atemp == a[nex]:
                if btemp != b[nex]:
                    return False, None
                
            else:
                if x is not None:
                    if (atemp * x + btemp != a[nex] * x + b[nex])\
                    or (atemp * x + btemp) <= 0:
                        return False, None
                    
                else:
                    if (btemp-b[nex])%(a[nex]-atemp) > 0\
                    or (btemp-b[nex])//(a[nex]-atemp) <= 0:
                        return False, None
                    
                    else:
                        x = (btemp-b[nex])//(a[nex]-atemp)

    return True, x

def find_range(a, b):
    upper = INF
    lower = -INF
    for ai, bi in zip(a,b):
        if ai < 0:
            upper = min(upper, bi)
        else:
            lower = max(lower, -bi)
            
    return max(0, upper-lower-1)

def confirm(a, b, x):
    for ai, bi in zip(a,b):
        if ai*x + bi <= 0:
            return 0
        
    return 1

res, x = dfs(graph, 0, None)

if not res:
    print(0)
    
elif x is not None:
    print(confirm(a,b,x))
    
else:
    print(find_range(a,b))

Solution (Python):
import sys
from collections import deque
N,M=map(int,input().split())
table=[[] for i in range(N)]
for i in range(M):
    u,v,s=map(int,input().split())
    table[u-1].append((v-1,s))
    table[v-1].append((u-1,s))
L=[0]*N
T=[1]*N
visit=[False]*N
h=deque()
h.append([0,1])
visit[0]=True
flag=True

K=[]

while h:
    x,t=h.popleft()
    for y,s in table[x]:
        if visit[y]:
            if T[y]==T[x]:
                flag=False
                K.append((x,y,s))
            else:
                if L[y]+L[x]!=s:
                    print(0)
                    sys.exit()
            continue
        T[y]=-t
        visit[y]=True
        L[y]=s-L[x]
        h.append([y,-t])
    
    
if not flag:
    x,y,s=K[0]
    t=T[x]
    u=L[x]+L[y]-s
    if u%2!=0:
        print(0)
        sys.exit()
    u=u//2
    for i in range(N):
        if T[i]==t:
            L[i]-=u
        else:
            L[i]+=u
    for x,y,s in K:
        if L[x]+L[y]!=s:
            print(0)
            sys.exit()
    for i in range(N):
        if L[i]<=0:
            print(0)
            sys.exit()
    print(1)
    sys.exit()
a=10**13
c=10**13


for i in range(N):
    if T[i]==1:
        a=min(a,L[i])
        
    else:
        c=min(c,L[i])
        
print(max(0,c+a-1))

Solution (Python):
from collections import deque
import sys
N,M=map(int,input().split())
table=[[] for i in range(N)]
ans=[]
for i in range(M):
    a,b,c=map(int,input().split())
    table[a-1].append((b-1,c))
    table[b-1].append((a-1,c))
    ans.append((a-1,b-1,c))
h=deque()
inf=-10**13
h.append(0)
flag=True
visit=[(inf,0)]*N
visit[0]=(0,0)
tree=[]
while h:
    x=h.popleft()
    for y,d in table[x]:
        if visit[y][0]!=inf and visit[y][1]==visit[x][1]:
            flag =False
            tree.append((x,y,d))
        elif visit[y][0]!=inf:
            if (visit[x][0]+visit[y][0])!=d:
                print(0)
                sys.exit()
        if visit[y][0]==inf:
            t=(visit[x][1]+1)%2
            visit[y]=(d-visit[x][0],t)
            h.append(y)
if flag:
    mi=-inf
    ma=-inf
    for i in range(N):
        if visit[i][1]==0:
            mi=min(mi,visit[i][0])
        else:
            ma=min(ma,visit[i][0])
    print(max(0,ma+mi-1))
    sys.exit()
a,b,c=tree[0]
s=visit[a][1]
t=visit[a][0]+visit[b][0]
w=(c-t)//2
for i in range(N):
    if visit[i][1]==s:
        x=visit[i][0]
        visit[i]=(x+w,s)
    else:
        x=visit[i][0]
        visit[i]=(x-w,(s+1)%2)
for x,y,d in ans:
    if (visit[x][0]+visit[y][0])!=d:
        print(0)
        sys.exit()
for i in range(N):
    if visit[i][0]<=0:
        print(0)
        sys.exit()
print(1)

Solution (Python):
from collections import deque
import sys
N,M=map(int,input().split())
table=[[] for i in range(N)]
ans=[]
for i in range(M):
    a,b,c=map(int,input().split())
    table[a-1].append((b-1,c))
    table[b-1].append((a-1,c))
    
h=deque()
inf=-10**13
h.append(0)
flag=True
visit=[(inf,0)]*N
visit[0]=(0,0)
tree=[]
while h:
    
    x=h.popleft()
    for y,d in table[x]:
        if visit[y][0]!=inf and visit[y][1]==visit[x][1]:
            flag =False
            tree.append((x,y,d))
        elif visit[y][0]!=inf:
            if (visit[x][0]+visit[y][0])!=d:
                print(0)
                sys.exit()
        elif visit[y][0]==inf:
            t=(visit[x][1]+1)%2
            visit[y]=(d-visit[x][0],t)
            h.append(y)



if flag:
    mi=-inf
    ma=-inf
    for i in range(N):
        if visit[i][1]==0:
            mi=min(mi,visit[i][0])
        else:
            ma=min(ma,visit[i][0])
    print(max(0,ma+mi-1))
    sys.exit()

a,b,c=tree[0]
s=visit[a][1]
t=visit[a][0]+visit[b][0]
if (c -t)%2==1:
    print(0)
    sys.exit()
w=(c-t)//2
dp=[inf]*N
if s==0:
    dp[0]=w
else:
    dp[0]=-w

k=deque()
k.append(0)
while k:
    x =k.popleft()
    for y,d in table[x]:
        if dp[y]!=inf and (dp[x]+dp[y])!=d:
            print(0)
            sys.exit()
        if dp[y]==inf:
            dp[y]=d-dp[x]
            k.append(y)
for i in range(N):
    if dp[i]<=0:
        print(0)
        sys.exit()
print(1)

Solution (Python):
n,m = map(int,input().split())
p = []
for i in range(m):
    x1,y1,z1,=[int(i) for i in input().split()]
    p.append([x1-1,y1-1,z1])
cost = [[] for i in range(n)]
for path in p:
    cost[path[0]].append((path[1],path[2]))
    cost[path[1]].append((path[0],path[2]))
zan = [[float("inf"),float("inf")] for i in range(n)]
zan[0] = (1,0)
tan =[(0,0)]
e = 0
while len(tan):
  i,j = tan.pop()
  for a,b in cost[i]:
    if (zan[a][0] != float("inf")):
      if abs((j)-zan[a][1]) == 1:
        pass
      elif ((j)-zan[a][1])%2 == 1:
        if zan[a][0] != b - zan[i][0]:
          e=1
          tan = []
          break
      else:
        e = 2
        if zan[a][0] != b - zan[i][0]:
          e = 3
          x = zan[a][0] + zan[i][0]
          if (b-x)% 2 != 0:
            e = 4
            tan = []
            break
          ano = zan[a][0] + (b-x)//2
          ino = zan[i][0] + (b-x)//2
          iti = (j)-zan[a][1]
          zan = [[float("inf"),float("inf")] for i in range(n)]
          zan[a] = (ano,0)
          kime = a
          zan[i] = (ino,iti)
          tan = []
          break
    zan[a] = (b - zan[i][0],j+1)
    tan.append((a,j+1))
  cost[i] = []
if e == 1:
  print(0)
elif e == 2:
  f = 0
  for i in range(n):
    if zan[i][0]<= 0:
      f = 1
      break
  if f == 0:
    print(1)
  else:
    print(0)
elif e == 4:
  print(0)
elif e == 0:
  syou =0
  f = 0
  dai = float("inf")
  for a,b in zan:
    if b %2 ==0:
      if a < 1:
        syou = max(syou,-a+1)
    else:
      if a > 0:
        dai = min(dai,a-1)
      else:
        f = 1
        break
  if f == 1:
    print(0)
  else:
    if dai >= syou:
      print(dai-syou+1)
    else:
      print(0)
elif e == 3:
  tan =[(kime,0)]
  cost = [[] for i in range(n)]
  for path in p:
    cost[path[0]].append((path[1],path[2]))
    cost[path[1]].append((path[0],path[2]))
  while len(tan):
      i,j = tan.pop()
      for a,b in cost[i]:
        if (zan[a][0] != float("inf")):
          if abs((j)-zan[a][1]) == 1:
            pass
          elif ((j)-zan[a][1])%2 == 1:
            if zan[a][0] != b - zan[i][0]:
              e=1
              tan = []
              break
          else:
            if zan[a][0] != b - zan[i][0]:
              e = 1
              break
        zan[a] = (b - zan[i][0],j+1)
        tan.append((a,j+1))
      cost[i] = []
  if e == 1:
    print(0)
  else:
    f = 0
    for i in range(n):
      if zan[i][0]<= 0:
        f = 1
        break
    if f == 0:
      print(1)
    else:
      print(0)

Solution (Python):
n,m = map(int,input().split())
p = []
for i in range(m):
    x1,y1,z1,=[int(i) for i in input().split()]
    p.append([x1-1,y1-1,z1])
cost = [[] for i in range(n)]
for path in p:
    cost[path[0]].append((path[1],path[2]))
    cost[path[1]].append((path[0],path[2]))
zan = [[float("inf"),float("inf")] for i in range(n)]
zan[0] = (1,0)
tan =[(0,0)]
e = 0
while len(tan):
  i,j = tan.pop()
  for a,b in cost[i]:
    if (zan[a][0] != float("inf")):
      if abs((j)-zan[a][1]) == 1:
        pass
      elif ((j)-zan[a][1])%2 == 1:
        if zan[a][0] != b - zan[i][0]:
          e=1
          tan = []
          break
      else:
        e = 2
        if zan[a][0] != b - zan[i][0]:
          e = 3
          x = zan[a][0] + zan[i][0]
          if (b-x)% 2 != 0:
            e = 4
            tan = []
            break
          ano = zan[a][0] + (b-x)//2
          ino = zan[i][0] + (b-x)//2
          iti = (j)-zan[a][1]
          zan = [[float("inf"),float("inf")] for i in range(n)]
          zan[a] = (ano,0)
          kime = a
          zan[i] = (ino,iti)
          tan = []
          break
    zan[a] = (b - zan[i][0],j+1)
    tan.append((a,j+1))
  cost[i] = []
if e == 1:
  print(0)
elif e == 2:
  f = 0
  for i in range(n):
    if zan[i][0]<= 0:
      f = 1
      break
  if f == 0:
    print(1)
  else:
    print(0)
elif e == 4:
  print(0)
elif e == 0:
  syou =0
  f = 0
  dai = float("inf")
  for a,b in zan:
    if b %2 ==0:
      if a < 1:
        syou = max(syou,-a+1)
    else:
      if a > 0:
        dai = min(dai,a-1)
      else:
        f = 1
        break
  if f == 1:
    print(0)
  else:
    if dai >= syou:
      print(dai-syou+1)
    else:
      print(0)
elif e == 3:
  tan =[(kime,0)]
  cost = [[] for i in range(n)]
  for path in p:
    cost[path[0]].append((path[1],path[2]))
    cost[path[1]].append((path[0],path[2]))
  while len(tan):
      i,j = tan.pop()
      for a,b in cost[i]:
        if (zan[a][0] != float("inf")):
          if abs((j)-zan[a][1]) == 1:
            pass
          elif ((j)-zan[a][1])%2 == 1:
            if zan[a][0] != b - zan[i][0]:
              e=1
              tan = []
              break
          else:
            if zan[a][0] != b - zan[i][0]:
              e = 1
              break
        zan[a] = (b - zan[i][0],j+1)
        tan.append((a,j+1))
      cost[i] = []
  if e == 1:
    print(0)
  else:
    f = 0
    for i in range(n):
      if zan[i][0]<= 0:
        f = 1
        break
    if f == 0:
      print(1)
    else:
      print(0)

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

n, m = map(int, input().split())

maxS = 0
vMaxS = -1
adjL = [[] for v in range(n)]
for i in range(m):
    u, v, s = map(int, input().split())
    adjL[u-1].append((v-1, s))
    adjL[v-1].append((u-1, s))
    if s > maxS:
        maxS = s
        vMaxS = u-1


if maxS == 2:
    print(1)
    exit()


def DFS(vNow):
    if len(zRange[vNow]) > 1: return
    zFr, zTo, dz = zRange[vNow][0]
    for v2, s in adjL[vNow]:
        
        zRange[v2].append((s - zFr, s - zTo, -dz))
        DFS(v2)


zRange = [[] for v in range(n)]
zRange[vMaxS].append((1, maxS-1, 1)) 
DFS(vMaxS)



iRange = [[] for v in range(n)]
for v, zR in enumerate(zRange):
    zR = list(set(zR)) 
    if len(zR) > 2:
        
        print(0)
        exit()
    elif len(zR) == 2:
        s1, ds = zR[0][0], zR[0][2]
        t1, dt = zR[1][0], zR[1][2]
        if ds == dt:
            
            print(0)
            exit()
        else:
            
            iC = (s1 - t1) / (dt - ds)
            if iC == int(iC) and 0 <= iC <= maxS-2 and s1 + ds * iC > 0:
                iRange[v] = [int(iC), int(iC)]
            else:
                print(0)
                exit()
    else:
        
        s1, ds = zR[0][0], zR[0][2]
        if ds == 1:
            iFr, iTo = max(0, 1-s1), maxS-2
        else:
            iFr, iTo = 0, min(s1-1, maxS-2)

        if iFr <= iTo:
            iRange[v] = [iFr, iTo]
        else:
            print(0)
            exit()


iRange = list(zip(*iRange)) 
iFr = max(iRange[0])
iTo = min(iRange[1])
if iFr <= iTo:
    print(iTo - iFr + 1)
else:
    print(0)

Solution (Python):
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

setrecursionlimit(10**6)
n, m = map(int, raw_input().split())
edges = [[] for _ in range(n)]

for i in range(m):
  u, v, s = map(int, raw_input().split())
  u, v = u-1, v-1
  edges[u].append((s, v))
  edges[v].append((s, u))

def quit(x):
  print(x)
  exit()

cond = [[None] * n for _ in range(2)]
cond[0][0] = 0

INF = 10**16

visited = [False] * n

def walk(x):
  if visited[x]:
    return
  visited[x] = True
  for s, y in edges[x]:
    for sig in range(2):
      if cond[sig][x] is not None:
        p = cond[sig][x]
        if cond[1-sig][y] is None or cond[1-sig][y] == s - p:
          cond[1-sig][y] = s - p
        else:
          quit(0)
    walk(y)

walk(0)

for i in range(n):
  if cond[0][i] is not None and cond[1][i] is not None:
    x = (cond[1][i] - cond[0][i]) // 2
    for j in range(n):
      if cond[0][j] is not None and cond[0][j] + x <= 0:
        quit(0)
      if cond[1][j] is not None and cond[1][j] - x <= 0:
        quit(0)
      if cond[0][j] is not None and cond[1][j] is not None and x + cond[0][j] != cond[1][j] - x:
        quit(0)
    quit(1)

pmin = min(p for p in cond[0] if p is not None)
nmin = min(p for p in cond[1] if p is not None)

print(max(0, nmin + pmin - 1))

Solution (Python):
from sys import stdin, stdout
from itertools import repeat
def main():
    n, m, = map(int, stdin.readline().split())
    dat = map(int, stdin.read().split(), repeat(10, 3 * m))
    la = [None] * (n + 1)
    xt = [None] * (3 * m)
    j = 0
    for i in xrange(m):
        x, y = dat[j], dat[j+1]
        xt[j] = la[y]
        la[y] = j
        j += 1
        xt[j] = la[x]
        la[x] = j
        j += 2
    st = [1]
    pu = st.append
    po = st.pop
    col = [0] * (n + 1)
    col[1] = 1
    f = None
    par = [None] * (n + 1)
    while st:
        x = po()
        y = la[x]
        while y is not None:
            z = dat[y]
            if not col[z]:
                col[z] = col[x] ^ 3
                par[z] = (x, dat[y/3*3+2])
                pu(z)
            elif col[z] == col[x] and f is None:
                f = (x, z)
                s = dat[y/3*3+2]
            y = xt[y]
    dp = [None] * (n + 1)
    if f is not None:
        px = []
        pz = []
        x, z = f
        while x != 1:
            px.append(par[x])
            x = par[x][0]
        while z != 1:
            pz.append(par[z])
            z = par[z][0]
        while px and pz and px[-1] == pz[-1]:
            px.pop()
            pz.pop()
        px += pz[::-1]
        k = [x[1] for x in px]
        s += sum(k)
        if s % 2:
            print 0
            return
        z = s / 2 - sum(k[::2])
        dp[f[1]] = z
        pu(f[1])
        while st:
            x = po()
            if dp[x] <= 0:
                print 0
                return
            y = la[x]
            while y is not None:
                z = dat[y]
                s = dat[y/3*3+2]
                if dp[z] is None:
                    dp[z] = s - dp[x]
                    pu(z)
                elif dp[z] + dp[x] != s:
                    print 0
                    return
                y = xt[y]
        print 1
        return
    pu(1)
    dp[1] = 0
    while st:
        x = po()
        y = la[x]
        while y is not None:
            z = dat[y]
            s = dat[y/3*3+2]
            if dp[z] is None:
                dp[z] = s - dp[x]
                pu(z)
            elif dp[z] + dp[x] != s:
                print 0
                return
            y = xt[y]
    x = 1 - min(dp[i] for i in xrange(1, n + 1) if col[i] == 1)
    for i in xrange(1, n + 1):
        if col[i] == 1:
            dp[i] += x
        else:
            dp[i] -= x
    x = min(dp[i] for i in xrange(1, n + 1) if col[i] == 2)
    if x <= 0:
        print 0
    else:
        print x
main()

Solution (Python):

from collections import deque

n, m = map(int, input().split())
G = dict()
for i in range(1, n+1):
    G[i] = dict()
    
for _ in range(m):
    u, v, s = map(int, input().split())
    G[u][v] = s
    G[v][u] = s

case = 1

done_flg = [0]*(n+1)
res_list = [0]*(n+1)
plmi_flg = [0]*(n+1)

queue = deque([1])
done_flg[1] = 1
plmi_flg[1] = 1

dif_list = []

while len(queue) > 0:
    u = queue.popleft()
    for v in G[u].keys():
        if done_flg[v] == 0:
            done_flg[v] = 1
            res_list[v] = G[u][v] - res_list[u]
            plmi_flg[v] = -plmi_flg[u]
            queue.append(v)
        elif plmi_flg[v] == -plmi_flg[u]:
            if res_list[v] != G[u][v] - res_list[u]:
                case = 9
                break
        else:
            d = G[u][v] - res_list[u] - res_list[v]
            if d % 2 == 1:
                case = 9
                break
            else:
                dif_list.append((d // 2)*plmi_flg[u])
                case = 2
    if case == 9:
        break
            
            

if case == 9:
    print(0)
elif case == 2:
    d = dif_list[0]
    check1 = True
    for d_ in dif_list:
        if d_ != d:
            check1 = False
    if check1 == False:
        print(0)
    else:
        for i in range(n+1):
            if plmi_flg[i]==1:
                res_list[i] += d
            elif plmi_flg[i]==-1:
                res_list[i] -= d
        if min(res_list[1:]) > 0:
            print(1)
        else:
            print(0)
elif case == 1:
    res_min_1 = min([res_list[i] for i in range(1, n+1) if plmi_flg[i]==1])
    res_min_2 = min([res_list[i] for i in range(1, n+1) if plmi_flg[i]==-1])
    r = max(0, (res_min_2 - 1) - (-res_min_1 + 1) + 1)
    print(r)

Solution (Python):


import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq


sys.setrecursionlimit(100000)


def solve(f):
    n, m = f.read_int_list()
    g = collections.defaultdict(list)
    g2 = {}
    for _ in xrange(m):
        u, v, s = f.read_int_list()
        g[u].append((v, s))
        g[v].append((u, s))
        if u < v:
            g2[(u,v)] = s
        else:
            g2[(v,u)] = s

    vis = [None] * (n+1)
    vis[1] = (1, 0)
    res = set()

    def dfs(v):
        for vi, si in g[v]:
            if vis[vi] is not None:
                if v > vi:
                    res.add((vi,v))
                else:
                    res.add((v,vi))
            else:
                vis[vi] = (vis[v][0]*-1, si-vis[v][1])
                dfs(vi)

    dfs(1)

    a = None
    for u, v in res:
        aa = vis[u][0]+vis[v][0]
        if aa == 0:
            if g2[(u,v)] != vis[u][1] + vis[v][1]: return 0
        else:
            bb = g2[(u,v)]-vis[u][1]-vis[v][1]
            a2 = bb / aa
            if aa*a2 != bb: return 0
            if a is not None and a != a2: return 0
            a = a2

    a1min = a2min = float('inf')
    a1max = a2max = -float('inf')
    for i in xrange(1,n+1):
        if vis[i][0] == 1:
            a1min = min(vis[i][1], a1min)
            a1max = max(vis[i][1], a1max)
        else:
            a2min = min(vis[i][1], a2min)
            a2max = max(vis[i][1], a2max)

    
    amax = a2min-1
    amin = max(1, -a1min+1)
    
    if amax < amin:
        return 0
    else:
        if a is not None:
            return min(1, amax-amin+1)
        else:
            return amax-amin+1


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case 
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Solution (Python):
import sys


def check(k, flag=False):
    fixed = [-1] * n
    q = [(0, k, False, None)]
    has_non_bipartite_loop = False
    while q:
        v, m, is_odd, a = q.pop()
        
        if fixed[v] != -1:
            p, was_odd = fixed[v]
            if is_odd == was_odd:
                if m != p:
                    return 0
                continue
            else:
                if m == p:
                    has_non_bipartite_loop = True
                    continue
                if flag:
                    return 0
                d = m - p if is_odd else p - m
                if d < 0:
                    return 0
                if d % 2:
                    return 0
                return check(k + d // 2, True)
        else:
            fixed[v] = (m, is_odd)

        for u, s in links[v]:
            if s - m < 1:
                if not is_odd:
                    return 0
                return check(k + m - s + 1, False)
            if u == a:
                continue
            q.append((u, s - m, not is_odd, v))

    if has_non_bipartite_loop:
        return 1

    min_is_odd = float('inf')
    for m, is_odd in fixed:
        if is_odd:
            min_is_odd = min(min_is_odd, m)
    return min_is_odd


n, m = map(int, input().split())
links = [set() for _ in range(n)]
for line in sys.stdin.readlines():
    u, v, s = map(int, line.split())
    u -= 1
    v -= 1
    links[u].add((v, s))
    links[v].add((u, s))
print(check(1))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    a = [LI() for _ in range(m)]
    e = collections.defaultdict(list)
    for u,v,s in a:
        e[u].append((v,s))
        e[v].append((u,s))

    f = collections.defaultdict(bool)
    t = [None] * (n+1)
    t[e[1][0][0]] = -1000000
    nf = set()
    q = [e[1][0][0]]
    r = None
    while q:
        i = q.pop()
        for v,s in e[i]:
            if f[v]:
                continue
            if t[v] is None:
                t[v] = s - t[i]
                q.append(v)
            elif t[v] != s - t[i]:
                if v in nf:
                    return 0
                tv = (t[v] + s - t[i]) // 2
                t = [None] * (n+1)
                t[v] = tv
                nf.add(v)
                q = [v]
                break
        if nf:
            f = collections.defaultdict(bool)
        else:
            f[i] = True
    t[0] = inf
    t2 = t[:]
    tmi = t.index(min(t))
    f = collections.defaultdict(bool)
    t = [None] * (n+1)
    t[tmi] = 1
    nf = set()
    q = [tmi]
    r = None
    while q:
        i = q.pop()
        for v,s in e[i]:
            if f[v]:
                continue
            if t[v] is None:
                t[v] = s - t[i]
                q.append(v)
            elif t[v] != s - t[i]:
                if v in nf:
                    return 0
                tv = (t[v] + s - t[i]) // 2
                t = [None] * (n+1)
                t[v] = tv
                nf.add(v)
                q = [v]
                break
        if nf:
            f = collections.defaultdict(bool)
        else:
            f[i] = True
    r = inf
    if t[1:] == t2[1:]:
        if min(t[1:]) > 0:
            return 1
        return 0
    for i in range(1,n+1):
        if t[i] < 0:
            return 0
        if t[i] > t2[i]:
            continue
        if r > t[i]:
            r = t[i]


    return r



print(main())

Solution (Python):
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

setrecursionlimit(10**6)

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

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

n, m = reads()

d = dict()
edges = [[] for _ in range(n)]

for i in range(m):
  u, v, s = reads()
  u, v = u-1, v-1
  edges[u].append((s, v))
  edges[v].append((s, u))

def quit(x):
  print(x)
  exit()

cond = [[None] * n for _ in range(2)]
cond[0][0] = 0

INF = 10**16

visited = [False] * n

def walk(x):
  if visited[x]:
    return
  visited[x] = True
  for s, y in edges[x]:
    for sig in range(2):
      if cond[sig][x] is not None:
        p = cond[sig][x]
        if cond[1-sig][y] is None or cond[1-sig][y] == s - p:
          cond[1-sig][y] = s - p
        else:
          quit(0)
    walk(y)

walk(0)

for i in range(n):
  if cond[0][i] is not None and cond[1][i] is not None:
    x = (cond[1][i] - cond[0][i]) // 2
    for i in range(n):
      if cond[0][i] is not None and cond[0][i] + x <= 0:
        quit(0)
      if cond[1][i] is not None and cond[1][i] - x <= 0:
        quit(0)
      if cond[0][i] is not None and cond[1][i] is not None and x + cond[0][i] != cond[1][i] - x:
        quit(0)
    quit(1)

pmin = min(p for p in cond[0] if p is not None)
nmin = min(p for p in cond[1] if p is not None)

print(max(0, nmin + pmin - 1))