Quarrel (Codeforces 29E)
Tags: Others, shortest paths

Friends Alex and Bob live in Bertown. In this town there are n crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number n.One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads n and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving. The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.If the required routes don't exist, your program should output -1.

Input: The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 10000) — the amount of crossroads and the amount of roads. Each of the following m lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road.

Output: If the required routes don't exist, output -1. Otherwise, the first line should contain integer k — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain k + 1 integers — Bob's route, i.e. the numbers of k + 1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them.


Sample Inputs:
2 1
1 2

7 5
1 2
2 7
7 6
2 3
3 4

7 6
1 2
2 7
7 6
2 3
3 4
1 5

Sample Outputs:
1
1 2
2 1

-1

6
1 2 3 4 3 2 7
7 6 7 2 1 5 1

Solution (Python):
import sys
from collections import deque
readline = sys.stdin.readline
(N, M) = [int(w) for w in readline().split()]
city = [[] for _ in range(N + 1)]
for _ in range(M):
    (u, v) = [int(w) for w in readline().split()]
    city[u].append(v)
    city[v].append(u)

def gen_dists(node: int) -> list:
    result = [N + 1] * (N + 1)
    dq = deque([node])
    result[node] = 1
    while dq:
        u = dq.popleft()
        for v in city[u]:
            if result[v] <= result[u] + 1:
                continue
            result[v] = result[u] + 1
            dq.append(v)
    return result
dist_alex = gen_dists(1)
dist_bob = gen_dists(N)
if dist_alex[-1] > N:
    print(-1)
    exit(0)
seen = {(1, N, 0): (-1, -1, -1)}
que = deque([(1, N, 0, 0)])
target = (N, 1, 0)
while que:
    (u, v, status, step) = que.popleft()
    if status == 0:
        for v1 in city[v]:
            if (u, v1, 1) in seen:
                continue
            seen[u, v1, 1] = (u, v, status)
            if dist_alex[v1] < dist_alex[v]:
                que.appendleft((u, v1, 1, step))
            else:
                que.append((u, v1, 1, step))
    elif status == 1:
        for u1 in city[u]:
            if u1 == v:
                continue
            if (u1, v, 0) in seen:
                continue
            seen[u1, v, 0] = (u, v, status)
            if dist_bob[u1] < dist_bob[u]:
                que.appendleft((u1, v, 0, step + 1))
            else:
                que.append((u1, v, 0, step + 1))
            if target in seen:
                break
        if target in seen:
            break
result = [[], []]
while target in seen:
    if target[-1] == 0:
        result[0].append(target[0])
        result[1].append(target[1])
    target = seen[target]
if result[0]:
    print(len(result[0]) - 1)
    print(*result[1])
    print(*result[0])
else:
    print(-1)

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

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

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

def bfs(u):
    (q, k) = ([u], 0)
    dist = [inf] * l
    dist[u] = 0
    parent = [-1] * l
    while len(q) ^ k:
        i = q[k]
        (u, v) = divmod(i % n2, n + 1)
        di = dist[i]
        if not di % 2:
            for p in range(s[u], s[u + 1]):
                j = f(G[p], v) + n2
                if dist[j] == inf:
                    q.append(j)
                    dist[j] = di + 1
                    parent[j] = i
        else:
            for r in range(s[v], s[v + 1]):
                if u == G[r]:
                    continue
                j = f(u, G[r])
                if dist[j] == inf:
                    q.append(j)
                    dist[j] = di + 1
                    parent[j] = i
        k += 1
    return (dist, parent)
(n, m) = map(int, input().split())
(G, s) = make_graph(n, m)
n2 = (n + 1) * (n + 1)
l = 2 * n2
inf = pow(10, 9) + 1
(dist, parent) = bfs(f(1, n))
k = (dist[f(n, 1)] // 2 + 1) % (inf // 2 + 1) - 1
print(k)
if k == -1:
    exit()
(ans1, ans2) = ([n], [1])
now = f(n, 1)
while parent[now] ^ -1:
    now = parent[now]
    (u, v) = divmod(now, n + 1)
    if not dist[now] % 2:
        ans1.append(u)
    else:
        ans2.append(v)
ans = ' '.join(map(str, ans1[::-1])) + '\n' + ' '.join(map(str, ans2[::-1]))
sys.stdout.write(ans)

Solution (Python):
import sys
from collections import deque
readline = sys.stdin.readline
(N, M) = [int(w) for w in readline().split()]
city = [[] for _ in range(N + 1)]
for _ in range(M):
    (u, v) = [int(w) for w in readline().split()]
    city[u].append(v)
    city[v].append(u)

def gen_dists(node: int) -> list:
    result = [N + 1] * (N + 1)
    dq = deque([node])
    result[node] = 1
    while dq:
        u = dq.popleft()
        for v in city[u]:
            if result[v] <= result[u] + 1:
                continue
            result[v] = result[u] + 1
            dq.append(v)
    return result
dist_alex = gen_dists(1)
dist_bob = gen_dists(N)
if dist_alex[-1] > N:
    print(-1)
    exit(0)
seen = {(1, N, 0): (-1, -1, -1)}
que = deque([(1, N, 0, 0)])
target = (N, 1, 0)
while que:
    (u, v, status, step) = que.popleft()
    if status == 0:
        for v1 in city[v]:
            if (u, v1, 1) in seen:
                continue
            seen[u, v1, 1] = (u, v, status)
            if dist_alex[v1] < dist_alex[v]:
                que.appendleft((u, v1, 1, step))
            else:
                que.append((u, v1, 1, step))
    elif status == 1:
        for u1 in city[u]:
            if u1 == v:
                continue
            if (u1, v, 0) in seen:
                continue
            seen[u1, v, 0] = (u, v, status)
            if dist_bob[u1] < dist_bob[u]:
                que.appendleft((u1, v, 0, step + 1))
            else:
                que.append((u1, v, 0, step + 1))
            if target in seen:
                break
        if target in seen:
            break
result = [[], []]
while target in seen:
    if target[-1] == 0:
        result[0].append(target[0])
        result[1].append(target[1])
    target = seen[target]
if result[0]:
    print(len(result[0]) - 1)
    print(*result[1])
    print(*result[0])
else:
    print(-1)