Codejam 1B 2022. Thinking about Task 2
🌐 Codejam Taskxxxxxxxxxx
import networkx as nx,pylab as pl
def graph(minmax):
g=nx.MultiDiGraph()
n=len(minmax)
g.add_node('start0')
g.add_edge('start0','min0',weight=minmax[0][0])
g.add_edge('start0','max0',weight=minmax[0][1])
for i in range(n):
g.add_node('min%d'%i)
g.add_node('max%d'%i)
g.add_edge('min%d'%i,'max%d'%i,
weight=minmax[i][1]-minmax[i][0])
g.add_edge('max%d'%i,'min%d'%i,
weight=minmax[i][1]-minmax[i][0])
if i!=n-1:
g.add_edge('min%d'%i,'min%d'%(i+1),
weight=abs(minmax[i][0]-minmax[i+1][0]))
g.add_edge('min%d'%i,'max%d'%(i+1),
weight=abs(minmax[i][0]-minmax[i+1][1]))
g.add_edge('max%d'%i,'min%d'%(i+1),
weight=abs(minmax[i][1]-minmax[i+1][0]))
g.add_edge('max%d'%i,'max%d'%(i+1),
weight=abs(minmax[i][1]-minmax[i+1][1]))
return g
def path(g):
sum=10**12
gl=list(g.nodes)
min_path=[]
for node in [gl[-1],gl[-2]]:
for path in nx.all_simple_paths(g,'start0',node):
if set(path)==set(gl):
path_len=nx.path_weight(g,path,'weight')
print(' '.join(path),'=>',path_len)
if sum>path_len:
sum=path_len
min_path=path
return sum,min_path
xxxxxxxxxx
minmax=[[10,40],[20,60],[50,60],[100,110],[30,70]]
n=len(minmax); g=graph(minmax)
sum,min_path=path(g)
print('\n min_path:\n',' '.join(min_path),'=>',sum)
xxxxxxxxxx
for i in range(len(min_path)-1):
print((min_path[i],min_path[i+1]),
g.get_edge_data(min_path[i],min_path[i+1]))
xxxxxxxxxx
def gdraw(g,n):
fig=pl.figure(1,figsize=(8,6),dpi=60)
pos=nx.planar_layout(g)
nx.draw(
g,pos,with_labels=True,
font_color='white',node_size=1500,
node_color='slategray',edge_color='slategray')
el=[('min%d'%i,'max%d'%i) for i in range(n)]+\
[('max%d'%i,'min%d'%i) for i in range(n)]
nx.draw_networkx_edges(
g,pos,edgelist=el,
edge_color='darkred',width=2)
pl.show()
gdraw(g,n)