Egor in the Republic of Dagestan (Codeforces 1407E)
Tags: Greedy, shortest paths

Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are $$$n$$$ cities in the republic, some of them are connected by $$$m$$$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $$$1$$$, travel to the city $$$n$$$ by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $$$1$$$ to $$$n$$$, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $$$1$$$ to $$$n$$$ or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.

Input: The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) — the number of cities and the number of roads.The $$$i$$$-th of next $$$m$$$ lines contains three integers — $$$u_i$$$, $$$v_i$$$ and $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) — numbers of cities connected by road and its type, respectively ($$$0$$$ — night road, $$$1$$$ — morning road).

Output: In the first line output the length of the desired path (or $$$-1$$$, if it's possible to choose such schedule that there's no path from $$$1$$$ to $$$n$$$).In the second line output the desired schedule — a string of $$$n$$$ digits, where $$$i$$$-th digit is $$$0$$$, if the $$$i$$$-th city is a night one, and $$$1$$$ if it's a morning one.If there are multiple answers, print any.

Note: For the first sample, if we paint city $$$1$$$ white, the shortest path is $$$1 \rightarrow 3$$$. Otherwise, it's $$$1 \rightarrow 2 \rightarrow 3$$$ regardless of other cities' colors.For the second sample, we should paint city $$$3$$$ black, and there are both black and white roads going from $$$2$$$ to $$$4$$$. Note that there can be a road connecting a city with itself.

Sample Inputs:
3 4
1 2 0
1 3 1
2 3 0
2 3 1

4 8
1 1 0
1 3 0
1 3 1
3 2 0
2 1 0
3 4 1
2 4 0
2 4 1

5 10
1 2 0
1 3 1
1 4 0
2 3 0
2 3 1
2 5 0
3 4 0
3 4 1
4 2 1
4 5 0

Sample Outputs:
2
011

3
1101

-1
11111

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
(n, m) = map(int, input().split())
back = [[] for i in range(n)]
for _ in range(m):
    (u, v, w) = map(int, input().split())
    u -= 1
    v -= 1
    back[v].append((u, w))
out = [2] * n
outl = [-1] * n
outl[-1] = 0
q = deque([n - 1])
while q:
    v = q.popleft()
    for (u, w) in back[v]:
        if out[u] != w:
            out[u] = 1 - w
        elif outl[u] == -1:
            outl[u] = outl[v] + 1
            q.append(u)
out = [v if v != 2 else 1 for v in out]
print(outl[0])
print(''.join(map(str, out)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, y, s) = ([0] * (2 * m), [0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (v, u, w) = map(int, input().split())
        s[u + 2] += 1
        (x[i], x[i + 1]) = (u, v)
        y[i] = w
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    (G, W) = ([0] * m, [0] * m)
    for i in range(0, 2 * m, 2):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        W[s[j]] = y[i]
        s[j] += 1
    return (G, W, s)

def f(u, v):
    return u * (n + 1) + v

def bfs(s):
    (q, k) = ([s], 0)
    dist = [inf] * (n + 1)
    dist[s] = 0
    dp = [inf] * (2 * n + 2)
    while len(q) ^ k:
        i = q[k]
        di = dist[i]
        for v in range(s0[i], s0[i + 1]):
            (j, c) = (G[v], W[v])
            if dp[f(c, j)] == inf:
                dp[f(c, j)] = di + 1
            if max(dp[f(0, j)], dp[f(1, j)]) ^ inf and dist[j] == inf:
                dist[j] = di + 1
                q.append(j)
        k += 1
    return (dist, dp)
(n, m) = map(int, input().split())
(G, W, s0) = make_graph(n, m)
inf = pow(10, 9) + 1
(dist, dp) = bfs(n)
ans = (dist[1] + 1) % (inf + 1) - 1
print(ans)
ans = ['0' if dp[f(0, i)] >= dp[f(1, i)] else '1' for i in range(1, n + 1)]
sys.stdout.write(''.join(ans))

Solution (Python):
import sys
from math import ceil, gcd
from collections import deque
input = sys.stdin.buffer.readline
(n, m) = [int(i) for i in input().split()]
adj = [[] for i in range(n + 1)]
mark = [0] * (n + 1)
d = [-1] * (n + 1)
c = [-1] * (n + 1)
for i in range(m):
    (u, v, b) = [int(i) for i in input().split()]
    adj[v].append((u, b))
q = deque()
q.append(n)
d[n] = 0
mark[n] = 1
while q:
    f = q.popleft()
    for i in adj[f]:
        if mark[i[0]] == 0:
            if c[i[0]] == -1:
                if i[1] == 1:
                    c[i[0]] = 0
                else:
                    c[i[0]] = 1
            elif c[i[0]] == i[1]:
                d[i[0]] = d[f] + 1
                q.append(i[0])
                mark[i[0]] = 1
sys.stdout.write(str(d[1]))
sys.stdout.write('\n')
for i in range(1, n + 1):
    if c[i] == -1:
        sys.stdout.write(str(1))
    else:
        sys.stdout.write(str(c[i]))
sys.stdout.write('\n')