Problem:
   Problem Setting     Overview   Concept: In this programming contest, you will run a delivery service. Customers will place orders with your shop. Each order has a unique \text{ID} and should be delivered to the corresponding customer. Your delivery service has one car. The car will fetch the ordered item from the shop and deliver it to the customer.  Score: Your goal is to deliver as many items as possible, as quickly as possible in a given amount of time T_{\text{max}} . (Orders are expected until 0.95 \times T_{\text{max}} ).  Constraint: In this contest there is no constraint on the number of items you can place in the car. However, an item can only be loaded in the car, by fetching it from the shop, after the order has been placed.  Problem A/B: In problem A all order positions and times are given to the contestant in advance and the contestant algorithm shall optimize the moves of the car to make as many deliveries as possible as fast as possible. On the other hand, in problem B orders appear online, that is new orders appear, while you move your car to make as many deliveries as possible as fast as possible.          Specification of Time and Space:   Time: In this contest we model the progress of time by integer values 0 \le t < T_{\text{max}} .  Map: In this contest we model a map by a simple, undirected, and connected graph G=(V, E) , consisting of a set of vertices V and a set of edges E  Shop and customer locations: The vertices u \in V are labeled from 1 to |V| and the vertex u=1 denotes the location of your shop, while vertices u = 2,...,|V| denote locations of potential customers. Here, |V| denotes the number of elements of the set V .  Streets: Each edge \left\{ u, v \right\} \in E represents a street connecting the vertices u, v \in V . The corresponding length is given by an integer edge weight d_{u, v} \ge 1 .  Graph creation: The algorithm for generating the map graph based on a random seed is specified in the following pseudo-code. For further details, please see the sample code below.     Pseudo code: Map graph generator    Input: |V| , |E| , \mathrm{MaxDegree}=5   2d vertex grid:   First, find the largest integer R>0 such that |V| = R^{2} + r , with r being the smallest possible non-negative integer.  Then we plot points (x, y) on the 2d vertex grid (0 \leq x, y \lt R) .  For each point (x, y) add a uniform random offset dx, dy \in [0, 1] , giving the final vertex position (x + dx, y + dy)\in [0,R] \times [0,R] .  Finally, add the remaining r vertices at a uniform random position (x, y) with 0 \leq x, y \leq R .  Vertex labels u \in V are assigned by random shuffling. The shop is the vertex u=1 .     How we create Highways:   To generate a highway network, we create a complete graph G_{\text{comp}} on the vertex set u \in V , assigning each vertex pair u, v \in V \times V the Euclidean distance W_{u, v} as an edge weight.  Next, we construct a minimum spanning tree of G_{\text{comp}} . The |V|-1 edges of the minimum spanning tree are the highway network of the graph G . We assign each of those edges \left\{ u, v \right\} an edge weight d_{u,v} \leftarrow \lceil 2 \times W_{u, v} \rceil .     How we add side roads:   To create a network of side roads, we successively add |E|-(|V|-1) edges to the graph G as follows:  Update \mathrm{cost}(u,v) .  Among the vertex pairs \left( u, v \right) \in V\times V , not yet connected by an edge, select a pair with minimal \mathrm{cost}(u,v) .  Assign the edge weight d_{u,v} \leftarrow \lceil 4 \times W_{u, v} \rceil .    Here, \mathrm{cost}(u,v) is essentially based on the Euclidean distance of vertices, giving preference to connecting nearby vertices with low degree. In addition, preference is given to side roads along the rectangular grid, to avoid too many bridges. The detailed definitions are as follows:  Define \mathrm{degree}(u) , the degree of vertex u\in V as the number of incident edges.  Define \mathrm{color}(u) for each vertex u\in V according to its original position (x,y) on the vertex grid as:  If x+y is even : \mathrm{color}(u) = 0   If x+y is odd : \mathrm{color}(u) = 1   For the remaining r vertices : Assign a color \mathrm{color}(u) \in \left\{0,1\right\} at random.    Define a factor f(u,v) as follows:  If \mathrm{color}(u) and \mathrm{color}(v) are the same : Set \mathrm{f}(u,v) = 5   If \mathrm{color}(u) and \mathrm{color}(v) are different : Set \mathrm{f}(u,v) = 1     Define a factor g(u) as follows:  If \mathrm{degree}(u) \lt \mathrm{MaxDegree} : Set g(u)=1   If \mathrm{degree}(u) \geq \mathrm{MaxDegree} : Set g(u)=\infty     Finally, the cost is defined as follows:   \mathrm{cost}(u,v) = W_{u,v}\times \mathrm{degree}(u) \times \mathrm{degree}(v) \times f(u,v) \times g(u) \times g(v) .         How we assign order frequencies:   Assign each vertex u \in V an order frequency f_u \in \left\{0,1,2\right\} .  Init the order frequency of the shop vertex: f_1 \leftarrow 0 .  Init the order frequency of the other vertices: f_u \leftarrow 1  Now determine vertices with order frequency 2. For this draw a uniform random center point c=(c_x,c_y)\in [R/4,3R/4]\times[R/4,3R/4] and then for all vertices u=2,...,|V| do:  If \mathrm{EuclideanDistance}(c,u)\le R/8 + \mathrm{uniformRandom}[0,R/8] : f_{u} \leftarrow 2             Specification of Car Locations and Moves:  In order to make deliveries you will operate a delivery car, which can take positions and make moves as specified below.    Car position: A car can generally take two types of position:   on a vertex u \in V .  on an edge \left\{ u, v \right\} \in E . More specifically, it is located at a distance x  (0 \lt x \lt d_{u, v}) from u to v .     Car move: At each step 0 \le t < T_{\text{max}} you have to choose one of the following actions in order to control your delivery car.   stay : stay at the current position.  move w : Take one step towards vertex w \in V .   In case of choosing move w , w must obey the following constraints. A failure to obey these constraints results in a wrong answer WA .   w must be a vertex, i.e., w \in V .  If the car is on vertex u \in V , there must be an edge connecting u and v , i.e., \left\{ u, w \right\} \in E .  If the car is on the edge \left\{ u, v \right\} \in E , w must either be w = u or w = v .            Orders, Deliveries, and Constraints:   Orders: Throughout the contest each order is characterized by three quantities: A unique order ID, a vertex v \in V indicating the order destination, and the order time t at which the order appeared. For the detailed format see below.  Order generation: At each time 0 \le t \le T_{\text{last}} = 0.95 \times T_{\text{max}} up to one new order can appear with probability p_{\text{order}}(t) . In case there is an order, the order destination i is chosen from the vertex set V with probability proportional to the order frequency f_i . For details, see the pseudo-code below or the sample code further below.     Pseudo code: Order generation    Input: Last order time T_{\text{last}} and average order probability p_{\text{order}}(t) .   Init:  \mathrm{ID} \leftarrow 0 .  For each step t = 0, ..., T_{\text{last}} do:  Generate a uniform random number r \in [0,1] .   If  r \le p_{\text{order}}(t) :  Select a vertex position u \in V at random with probability proportional to the order frequency f_{u} of the vertex.   \mathrm{ID} \leftarrow \mathrm{ID} + 1   place order (new order ID, order time t , vertex position u \in V )     Else: place no order       Note: The average order probability is defined as follows:  p_{\text{order}}(t) =
\begin{cases}
t / T_{\text{peak}},  &
\text{if } 0\le t \lt T_{\text{peak}}, \\
(T_{\text{last}} - t) / (T_{\text{last}}- T_{\text{peak}}),  &
\text{if } T_{\text{peak}} \le t \lt T_{\text{last}}, \\
0, &
\text{if } T_{\text{last}} \le t,
\end{cases}  where T_{\text{last}}:=0.95 \times T_{\max} and T_{\text{peak}} is drawn randomly uniform from the interval [0, T_{\text{last}}] .  Note: The value of T_{\text{peak}} will not be given as an input.        Delivery: To deliver an order, the contestant must do the following steps after the order has been placed:  (1st) Move the car onto the shop: Note: When moving a car onto the shop, all orders with order time less than or equal to the current time, will be transfered into the car. On the other hand, orders which have not appeared yet, cannot be placed into the car.  (2nd) Move the car to the customer position: To finalize a delivery, move the car onto the vertex of the customer position. Note: Orders which have not been transfered into the car yet, will not be delivered, even if you arrive at the customer position.         Constraints: Throughout the contest, we assume each order has a unique \text{ID} and should be delivered to the corresponding customer. It is further assumed that an unlimited number of orders can be placed in the car.       Scoring   During the contest the total score of a submission is determined by summing the score of the submission with respect to 30 input cases.  After the contest a system test will be performed. To this end, the contestant's last submission will be scored by summing the score of the submission on 100 previously unseen input cases.  For each input case, the score is calculated as follows:  \text{Score} =
    \sum_{i \in D} {(T_{\text{max}})}^{2} - {(\mathrm{waitingTime}_i)}^{2},  Here we use the following definitions:   D : the set of orders delivered until t=T_{\text{max}}  the waiting time of the i th order: \mathrm{waitingTime}_i = \mathrm{deliveredTime}_i - \mathrm{orderedTime}_i .  Note that an input case giving the output WA will receive 0 points.        Particulars of Problem A  In problem A we pass all orders which appear at time 0 \le t < 0.95 \times T_{\text{max}} as an input to the contestant code. The task is to provide an algorithm which optimizes the moves of the car such that the above score becomes maximal.       Input Format  Input is provided in the following form:  |V|  |E|  u_{1}  v_{1}  d_{u_{1}, v_{1}}  u_{2}  v_{2}  d_{u_{2}, v_{2}} : u_{|E|}  v_{|E|}  d_{u_{|E|}, v_{|E|}}  T_{\text{max}}  \mathrm{info}_{0}  \mathrm{info}_{1} : \mathrm{info}_{T_{\text{max}}-1}    In the first line |V| denotes the number of vertices, while |E| denotes the number of edges.  The following |E| lines denote the edges of the graph. In particular, in the i th line u_{i} and v_{i} denote the edge connecting u_{i} and v_{i} and d_{u_{i}, v_{i}} the corresponding distance.  The following line denotes the number of steps T_{\text{max}} .   In the following line, \mathrm{info}_t is information about the order from the customer that occurs at time t . \mathrm{info}_t is given in the form:  N_{\text{new}}  \mathrm{new\_id}_1  \mathrm{dst}_1  \mathrm{new\_id}_2  \mathrm{dst}_2  \vdots  \mathrm{new\_id}_{N_{\text{new}}}  \mathrm{dst}_{N_{\text{new}}}     N_{\text{new}} represents the number of new orders which appear at time t .  The next N_{\text{new}} lines give the newly generated order information. The i -th order information indicates that the order ID \mathrm{new\_{id}}_i of the new order, while \mathrm{dst}_i denotes the vertex to which the customer wishes the order to be delivered.  Note: If N_{\text{new}}=0 , there are no new lines.       Requirements   All inputs are of non-negative integer value.   T_{\text{max}} = 10000   200 \leq |V| \leq 400    1.5 |V| \leq |E| \leq  2 |V|  1 \leq u_{i}, v_{i} \leq |V|  (1 \leq i \leq |E|)  1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil  (1 \leq i \leq |E|)  The given graph has no self-loops / multiple edges and is guaranteed to be connected.  0 \leq N_{\text{new}} \leq 1  1 \leq \mathrm{new\_id}_{i} \leq T_{\text{last}}+1  (1 \leq i \leq N_{\text{new}}) . Note: If all orders are generated by the order generation rule as explained above, the total number of orders is at most T_{\text{last}}+1 . Therefore, the possible range of \mathrm{new\_id}_{i} should be from 1 to T_{\text{last}}+1 .  2 \leq \mathrm{dst}_i \leq |V|  (1 \leq i \leq N_{\text{new}})  The order IDs \mathrm{new\_{id}}_i are unique.       Output Format  The Output expects T_{\text{max}} integers in the format specified below.  \mathrm{command}_{0}  \mathrm{command}_{1} : \mathrm{command}_{T_{\text{max}}-1}   In particular, \mathrm{command}_{i} shall specify the movement of the delivery car by using one of the following two options:  1) stay , if the car shall not move:  -1  2) move w , if the car shall be moved one step towards the neighboring vertex w  w  Note that in case of 2) w has to satisfy the following conditions:   w \in V  If the car is at vertex u : \left\{ u, w \right\} \in E .  If the car is on the edge \left\{ u, v \right\} , w must either satisfy u = w or v = w .        Input Example  5 7
1 2 5
5 3 4
2 4 8
1 5 1
2 3 3
4 5 3
4 3 9
4
1
1 2
1
2 5
1
3 4
0  Note that this input is an example of small size and does not meet the constraints of the contest.      Output Example  2
-1
1
5      Explanation  The example operates on a graph with |V| = 5 vertices, |E| = 7 edges, and T_{\text{max}} = 4 time steps. We now describe the orders which have occured and the movement of the car.  Time t=0  At time t=0 an order is placed at the shop. This order has ID = 1 and should be delivered to vertex 2 . Because your car is currently at vertex one, the order will be automatically transfered into your car. In this way, when your car is at the shop, all orders which have been made at present and before, will automatically be loaded into your car.  Time 0 → 1  You choose to move towards vertex move 2 . You will now move one step towards vertex 2.  Time t=1  A new order has appeared. It has ID =2 and shall be delivered at  vertex 5 .  Time 1 → 2  You decided to stay . You can now stay on the edge where you are.  Time t=2  A new order has appeared. It has ID =3 and shall be delivered at  vertex 4 .  Time 2 → 3  You decided to move move 1 back to vertex 1.
You are approaching one step towards vertex 1.
Doing a U-turn in this way is explicitly allowed.  Time t=3  New orders have not occurred. Now that you are at the vertex 1 (store), the orders with order ID 2, 3 are loaded into your car. In a similar way, whenever you return to the store, all the orders that have already been placed are loaded into your car automatically.  Time 3 → 4  Being at vertex 1 you choose move 5 . You are moving your car one step towards vertex 5 . You arrive at vertex 5 .  Time t=4  Since you arrived at vertex 5 , the order with order ID 2 can be delivered.      Sample Code A  A software toolkit for generation of input samples, scoring and testing on a local contestant environment, and  sample codes for beginners
is provided through the following link . In addition we provide software for visualizing the contestants results.

Solution (Python):
import sys
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False

MAXVISIT = 400
SPLITTHR = 44
HISTTHR = -1
SPLITTHR4 = 80
HISTTHR4 = 8

def ddprint(x):
  if DBG:
    print(x)
    sys.stdout.flush()

def trigger():
    return (len(loadhash) > 0)

def nxtnode():
    global lastnd, workreq, nxtndary
    tgt = workreq[0] if len(workreq)>0 else 1
    
    
    return nxtndary[lastnd][tgt]

def atdepot():
    return (lastnd==1 and distfromlast==0)

def stay():
    
    print(-1)
    sys.stdout.flush()

def readput():
    n = inn()
    for i in range(n):
        inn()

def readverd():
    v = input().strip()
    if v != 'OK':
        exit()
    readput()

def move():
    global distfromlast, lastnd, workreq, pendreq, loadhash
    nxtnd = nxtnode()
    
    print(nxtnd)
    sys.stdout.flush()
    distfromlast += 1
    if distfromlast == dist[lastnd][nxtnd]: 
        distfromlast = 0
        if nxtnd in workreq:
            workreq.remove(nxtnd)
        if nxtnd in loadhash:
                del loadhash[nxtnd]
        if nxtnd==1:
                for z in pendreq:
                    if z[1] not in loadhash:
                        loadhash[z[1]] = []
                    loadhash[z[1]].append(z[2])
                pendreq = []
        lastnd = nxtnd

def ufinit(n):
    global ufary, ufrank
    ufary = [i for i in range(n)]
    ufrank = [0] * n

def ufroot(i):
    p = ufary[i]
    if p==i:
        return p
    q = ufroot(p)
    ufary[i] = q
    return q

def ufmerge(i,j):
    global ufary, ufrank
    ri = ufroot(i)
    rj = ufroot(j)
    if ri==rj:
        return
    if ufrank[ri]>ufrank[rj]:
        ufary[rj] = ri
    else:
        ufary[ri] = rj
        if ufrank[ri]==ufrank[rj]:
            ufrank[rj] += 1

def setwork():
    global workreq, lastside, loadhash
    visset = set(loadhash.keys()) | set(workreq)
    vislist = list(visset)
    vv = len(vislist)
    if vv==1:
        workreq = vislist
        return
    if vv>SPLITTHR4 and sum(hist)>HISTTHR4:
        pt = [0,0,0,0]
        for x in vislist:
            suf = (0 if x in gr4[0] else \
              1 if x in gr4[1] else 2 if x in gr4[2] else 3)
            pt[suf] += sum([t-y for y in loadhash[x]])
        mx = max(pt)
        lastside = (0 if mx==pt[0] else \
            1 if mx==pt[1] else 2 if mx==pt[2] else 3)
        vislist = [x for x in vislist if x in gr4[lastside]]
        vv = len(vislist)
    elif vv>SPLITTHR and sum(hist)>HISTTHR:
        pt = [0,0]
        for x in vislist:
            suf = (0 if x in gr[0] else 1)
            pt[suf] += sum([t-y for y in loadhash[x]])
        lastside = (0 if pt[0]>=pt[1] else 1)
        vislist = [x for x in vislist if x in gr[lastside]]
        vv = len(vislist)
        lastside = 1 - lastside

    
    e = {}
    f = {}
    for x in vislist:
        e[x] = []
    ufinit(V+1)
    
    
    for _ in range(vv-1):
        mx = -1
        for i in e:
            for j in e:
                if ufroot(i)==ufroot(j):
                    continue
                df = dist[i][1] + dist[1][j] - dist[i][j]
                if df>mx:
                    mx = df
                    mxi = i
                    mxj = j
        i = mxi
        j = mxj
        
        e[i].append(j)
        e[j].append(i)
        ufmerge(i,j)
        if len(e[i])==2:
            f[i] = e[i]
            del e[i]
        if len(e[j])==2:
            f[j] = e[j]
            del e[j]
    
    
    
    ek = list(e.keys())
    p = ek[0]
    
    prev = p
    cur = e[p][0]
    workreq = [p,cur]
    for i in range(vv-2):
        p = cur
        cur = f[p][0]
        if cur==prev:
            cur = f[p][1]
        prev = p
        workreq.append(cur)

    acct = t
    prev = 1
    fwdpt = 0
    for i in range(len(workreq)):
        x = workreq[i]
        for y in loadhash[x]:
            fwdpt += acct - y
        acct += dist[prev][x]
        prev = x

    acct = t
    prev = 1
    revpt = 0
    for i in range(len(workreq)):
        x = workreq[len(workreq)-1-i]
        for y in loadhash[x]:
            revpt += acct - y
        acct += dist[prev][x]
        prev = x

    if revpt<fwdpt:
        workreq.reverse()
    

def findcorners():
    mx = -1
    for i in range(1,V+1):
        for j in range(1,V+1):
            d = dist[i][j]
            if d>mx:
                mx = d
                mxi = i
                mxj = j
    c1 = mxi
    c3 = mxj
    mx = -1
    for i in range(1,V+1):
        d = dist[i][c1]+dist[i][c3]
        if d>mx:
            mx = d
            mxi = i
    c2 = mxi
    mx = -1
    for i in range(1,V+1):
        d = dist[i][c1]+dist[i][c3]+dist[i][c2]
        if d>mx:
            mx = d
            mxi = i
    c4 = mxi
    d1 = dist[1][c1]
    d2 = dist[1][c2]
    d3 = dist[1][c3]
    d4 = dist[1][c4]
    if min(d1,d3)<min(d2,d4):
        z = (c2,c4)
    else:
        z = (c1,c3)

    a = []
    for i in range(2,V+1):
        df = dist[i][z[0]]-dist[i][z[1]]
        a.append((df,i))
    a.sort()
    g0 = [x[1] for x in a[:(V-1)//2]]
    g1 = [x[1] for x in a[(V-1)//2:]]
    
    
    
    
    
    
    

    tricent = 0
    if 3*d1 < min([d2,d3,d4]):
        tricent = c1
    elif 3*d2 < min([d1,d3,d4]):
        tricent = c2
    elif 3*d3 < min([d1,d2,d4]):
        tricent = c3
    elif 3*d4 < min([d1,d2,d3]):
        tricent = c4

    h0 = []
    h1 = []
    h2 = []
    h3 = []
    if tricent==0:
      for i in range(2,V+1):
        d1 = dist[i][c1]
        d2 = dist[i][c2]
        d3 = dist[i][c3]
        d4 = dist[i][c4]
        mn = min([d1,d2,d3,d4])
        if mn==d1:
            h0.append(i)
        elif mn==d2:
            h1.append(i)
        elif mn==d3:
            h2.append(i)
        elif mn==d4:
            h3.append(i)
    else:
        if tricent==c1:
            ccc = [c2,c3,c4]
        elif tricent==c2:
            ccc = [c1,c3,c4]
        elif tricent==c3:
            ccc = [c1,c2,c4]
        else:  
            ccc = [c1,c2,c3]
        for i in range(2,V+1):
            d1 = dist[i][ccc[0]]
            d2 = dist[i][ccc[1]]
            d3 = dist[i][ccc[2]]
            mn = min([d1,d2,d3])
            if mn==d1:
                h0.append(i)
            elif mn==d2:
                h1.append(i)
            else:  
                h2.append(i)
            

    return (g0,g1,h0,h1,h2,h3)


ddprint("start")


V, E = inm()
es = [[] for i in range(V+1)]
dist = [[9999]*(V+1) for i in range(V+1)]

for i in range(V+1):
    dist[i][i] = 0

for i in range(E):
    a, b, c = inm()
    
    es[a].append((b,c))
    es[b].append((a,c))
    dist[a][b] = dist[b][a] = c

if DBG:
    for i,z in enumerate(es):
        print(str(i)+' ' + str(z))


for k in range(1,V+1):
    for i in range(1,V+1):
        for j in range(1,V+1):
            dist[i][j] = min(dist[i][j], \
                           dist[i][k]+dist[k][j])
ddprint("WS done")

nxtndary = [[0]*(V+1) for i in range(V+1)]
for i in range(1,V+1):
    for j in range(1,V+1):
        if j==i:
            continue
        found = False
        for z in es[i]:
            k = z[0]
            if dist[i][j] == z[1]+dist[k][j]:
                nxtndary[i][j] = k
                found = True
                break
        if not found:
            print("nxtndary ERR")
            exit()

g0,g1,h0,h1,h2,h3 = findcorners()
gr = [g0,g1]
gr4 = [h0,h1,h2,h3]
lastside = 0

F = inl()
if len(F)==1:
    prob = 1
    tt = F[0]
else:
    prob = 2
    tt = inn()
pendreq = []
workreq = []
loadhash = {}
lastnd = 1
distfromlast = 0
hist = []
for t in range(tt):
    if DBG and t>3400:
        exit()

    
    n = inn()
    hist.append(n)
    if len(hist)>20:
        hist = hist[1:]
    if n==1:
        new_id, dst = inm()
        
        if not atdepot():
            pendreq.append((new_id, dst, t))
        else:
            if dst not in loadhash:
                loadhash[dst] = []
            loadhash[dst].append(t)
    if prob==2:
        readput()
    
    if atdepot():
        if trigger():
            setwork()
            if len(workreq)>0:
                move()
            else:
                stay()
        else:
            stay()
    else:
        move()
    if prob==2:
        readverd()

Solution (Python):

import time
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

vertex_number, edge_number = map(int, input().split())
 

 
A = [[0 for i in range(vertex_number+1)] for j in range(vertex_number+1)] 
for i in range(edge_number):
    j,k,d = map(int, input().split())
    A[j][k] = d
    A[k][j] = d
    
 

T_max = int(input())
info = []
 
for i in range(T_max):
    x = int(input())
    if x == 0:
        info.append([x])
    else:
        y,z = map(int, input().split())
        info.append([x,y,z])
 
 

D = [[0 for i in range(vertex_number+1)] for j in range(vertex_number+1)] 


for i in range(vertex_number+1):
    for j in range(vertex_number+1):
        if (i != 0) and (j != 0): 
            if i == j:             
                D[i][j] = 0
            elif A[i][j] == 0:      
                D[i][j] = float("inf")
            else: D[i][j] = A[i][j] 

D1,Prev = floyd_warshall(D,directed=False,return_predecessors=True)   
for i in range(vertex_number+1):
    for j in range(vertex_number+1):
        if D1[i][j] != float("inf"):
            D[i][j] = int(D1[i][j])



def Shortest_path(i,j): 
    SP = [j]
    x = Prev[i][j]
    while (x != i) and (x > 0):
        SP.insert(0,x)
        x = Prev[i][x]
    SP.insert(0,i)
    return SP
 

def Request(a,b): 
    R = []
    if a == b: 
        return R
    else:
        for i in range(b-a):
            if info[i+a+1] != [0]:
                if info[i+a+1][2] not in R:
                    R.append(info[i+a+1][2])
        return R
 
def Wt(a,b): 
    R = []
    WT = []
    if a == b: 
        return WT
    else:
        for i in range(b-a):
            if info[i+a+1] != [0]:
                if info[i+a+1][2] not in R:
                    WT.append(b-(i+a+1))
                    R.append(info[i+a+1][2])
        return WT

 
t = 0
t_start = 0
Root = []
counter = 0
while t < T_max-1:
    Req = [] 
    if Request(t_start,t) == []: 
        while (info[t] == [0]) and (t != T_max - 1):
            t += 1
            Root.append(-1)
        if t != T_max - 1:
            Req.append(info[t][2])
 
    else:
        Req = Request(t_start,t)

    W = Wt(t_start,t)
    '''
    print("現在時刻",t)
    print("はじめのリクエスト数",len(Req))
    '''
    rp = []
    Reqq = Req.copy()
    WW = W.copy()
    if counter == 1:
        
        for i in range(len(Req)):
            t_i = t - W[i]-t_start 
            for j in range(len(time_path)):
                if time_path[j] >= t_i:
                    rp = real_path[j:] 
                    break
            if (1 in rp) and (Req[i] in rp) and (rp.index(1) < rp.index(Req[i])):
                Reqq.remove(Req[i])
                WW.remove(W[i])
        Req = Reqq
        W = WW
    '''
    print("厳選後のリクエスト数",len(Req))
    '''
    t_start = t
    counter = 1
    if t != T_max - 1:
        
        t_path = 0       
        active_path = [1]
        real_path = []
        while Req != []:
            x = 0
            u = 0
            for i in range(len(Req)):
                if i == 0:
                    x = D[active_path[-1]][Req[0]]
                    u = Req[0]
                elif x > D[active_path[-1]][Req[i]]:
                    x = D[active_path[-1]][Req[i]]
                    u = Req[i]
            Req.remove(u)
            active_path.append(u)
            t_path += x
        t_path += D[active_path[-1]][1]
        active_path.append(1)
        t += t_path
 

        
        for i in range(len(active_path)):
            if i == 0:
                real_path =real_path + Shortest_path(active_path[i],active_path[i+1])
            elif i != len(active_path)-1:
                real_path.pop(-1)
                real_path =real_path + Shortest_path(active_path[i],active_path[i+1])
        for j in range(len(real_path)):
            if j < len(real_path)-1:
                for k in range(A[real_path[j]][real_path[j+1]]):
                    Root.append(real_path[j+1])
         
        time_path = []
        for i in range(len(real_path)):
            tt = 0
            if i == 0:
                time_path.append(0)
            else:
                tt += A[real_path[i-1]][real_path[i]]
                time_path.append(tt)


for i in range(T_max):
    if i < len(Root):
        print(Root[i])
    else:
        print(-1)