#!/usr/bin/python
# -*- coding: UTF-8 -*-
import tkMessageBox
from Tkinter import*
from math import floor

tk=Tk()
tk.title("Департамент сельских дел . Депо земледельческих орудий")
l=Label(tk,text="Главная счетная экспедиция. Транспортная задача",font="Arial 12")
c=Canvas(tk,width=720,height=680,bg='green')
e=Entry(tk)
l.pack()
e.pack()
c.pack()

ls,lc=input('servers as [s1,s2,...]='),input('clients as [c1,c2,...]=')
ss=reduce(lambda i,j:i+j,ls)
sc=reduce(lambda i,j:i+j,lc)
ads=adc=0
if ss-sc>0:
  lc.append(ss-sc)
  adc=1
if sc-ss>0:
  ls.append(sc-ss)
  ads=1
ms,nc=len(ls),len(lc)
m,n=max(ms,nc),min(ms,nc)
hl,hw=670./(m+1),720./(n+1)

class K:
  def __init__(self,x,y):
    self.x,self.y=x,y
    self.hl,self.hw=hl,hw
    self.c,self.tc,self.tcr=c,'',''
    self.tl,self.tr='',''
  def dron(self):
    self.c.create_rectangle((self.x,self.y,self.x+self.hw,self.y+self.hl),outline='black',fill='green',width=1)
    self.c.create_text((self.x+.3*self.hw,self.y+.5*self.hl),text=self.tc)
    self.c.create_text((self.x+.7*self.hw,self.y+.5*self.hl),text=self.tcr)
    self.c.create_text((self.x+.3*self.hw,self.y+self.hl-15),text=self.tl)
    self.c.create_text((self.x+self.hw-25,self.y+0.75*self.hl),text=self.tr)

lk,l=[],[]
for i in range(m+1):
  for j in range(n+1):
    l.append(K(j*hw,i*hl))
  lk.append(l)
  l=[]

def renew():
  for i in range(m+1):
    for j in range(n+1):
      lk[i][j].dron()

if m==ms and m>n:
  for i in range(m):
    lk[i][n].tl=ls[i]
  if ads:
    lk[m-1][n].tc='+'
  for j in range(n):
    lk[m][j].tc=lc[j]
  if adc:
    lk[m][n-1].tcr='+'
if m==nc and m>n:
  for i in range(m):
    lk[i][n].tl=lc[i]
  if adc:
    lk[m-1][n].tc='+'
  for j in range(n):
    lk[m][j].tc=ls[j]
  if ads:
    lk[m][n-1].tcr='+'
if m==n:
  for i in range(m):
    lk[i][n].tl=lc[i]
  if adc:
    lk[m-1][n].tc='+'
  for j in range(n):
    lk[m][j].tc=ls[j]
  if ads:
    lk[m][n-1].tcr='+'

renew()

def counter():
  index=0
  for i in range(m):
    for j in range(n):
      if  lk[i][j].tc!='':
          index+=1
  if m+n-index-1>=0: return 1
  else: return 0      
         

def sign_plan(event):
  i,j=int(floor(event.y/hl)),int(floor(event.x/hw))
  e.focus_set()
  s=e.get()
  if s:
    if lk[i][j].tc=='':
	if counter():
		lk[i][j].tc=float(s)
      		lk[i][n].tl-=float(s)
      		lk[m][j].tc-=float(s)
	else: pass
    else:       
      lk[i][j].tc+=float(s) 
      lk[i][n].tl-=float(s)
      lk[m][j].tc-=float(s)
      if lk[i][j].tc==0.0 :
        if counter(): pass
        else: lk[i][j].tc=''
  else: pass
  e.delete(0, END)
  lk[i][j].dron()
  lk[i][n].dron()
  lk[m][j].dron()


def sign_cost(event):
  i,j=int(floor(event.y/hl)),int(floor(event.x/hw))
  e.focus_set()
  s=e.get()
  lk[i][j].tcr=float(s)
  e.delete(0, END)
  renew()
  

def clear_plan(event):
  i,j=int(floor(event.y/hl)),int(floor(event.x/hw))
  lk[i][n].tl+=lk[i][j].tc
  lk[m][j].tc+=lk[i][j].tc
  lk[i][j].tc=''
  renew()


def enter(event):
  index=0
  for i in range(m):
    for j in range(n):
      if  lk[i][j].tc!='':
          index+=1
  if m+n-index-1!=0:
	tkMessageBox.showerror("Косяки !", "Количество заполненных клеток должно равняться "+str(m+n-1)+" !")
	return	

  count=0
  account=0
  U,V=[0],[]
  for p in range(1,m):
    U.append('')
  for q in range(n):
    V.append('')
  lt=[(i,j,lk[i][j].tcr) for i in range(m) for j in range(n) if lk[i][j].tc!='']
  while True:
    for a in lt:
      if U[a[0]]!='':
        V[a[1]]=a[2]-U[a[0]]
        del lt[lt.index(a)]
        continue
      if V[a[1]]!='':
        U[a[0]]=a[2]-V[a[1]]
        del lt[lt.index(a)]
        continue
    if '' in U or '' in V:
      print 'U=',U, '\nV=',V
      continue
    else:
      print 'U=',U, '\nV=',V
      break
  for i in range(m):
    for j in range(n):
      if lk[i][j].tl<0: lk[i][j].tl=''
      if lk[i][j].tc: account+=lk[i][j].tc*lk[i][j].tcr
      if lk[i][j].tcr-U[i]-V[j]<0:
        count+=1
        lk[i][j].tl=lk[i][j].tcr-U[i]-V[j]
        lk[i][j].dron()
  renew()
  if count:
    print 'Transport failed'
    print 'Amount=',account
  else:
    print 'Transport optimal!'
    print 'Amount=',account


tk.bind("<Button-1>",sign_plan)
tk.bind("<Button-3>",sign_cost)
tk.bind("<Double-Button-1>",clear_plan)
tk.bind("<Return>",enter)

tk.mainloop()

