The main characters have been omitted to be short.

You are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \ldots, p_m$ of $m$ vertexes; for each $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.

Define the sequence $v_1, v_2, \ldots, v_k$ of $k$ vertexes as good, if $v$ is a subsequence of $p$, $v_1 = p_1$, $v_k = p_m$, and $p$ is one of the shortest paths passing through the vertexes $v_1$, $\ldots$, $v_k$ in that order.

A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $p$ is good but your task is to find the shortest good subsequence.

If there are multiple shortest good subsequences, output any of them.

 


-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of vertexes in a graph. 

The next $n$ lines define the graph by an adjacency matrix: the $j$-th character in the $i$-st line is equal to $1$ if there is an arc from vertex $i$ to the vertex $j$ else it is equal to $0$. It is guaranteed that the graph doesn't contain loops.

The next line contains a single integer $m$ ($2 \le m \le 10^6$) — the number of vertexes in the path. 

The next line contains $m$ integers $p_1, p_2, \ldots, p_m$ ($1 \le p_i \le n$) — the sequence of vertexes in the path. It is guaranteed that for any $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.


-----Output-----

In the first line output a single integer $k$ ($2 \leq k \leq m$) — the length of the shortest good subsequence. In the second line output $k$ integers $v_1$, $\ldots$, $v_k$ ($1 \leq v_i \leq n$) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.


-----Examples-----
Input
4
0110
0010
0001
1000
4
1 2 3 4

Output
3
1 2 4 
Input
4
0110
0010
1001
1000
20
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

Output
11
1 2 4 2 4 2 4 2 4 2 4 
Input
3
011
101
110
7
1 2 3 1 3 2 1

Output
7
1 2 3 1 3 2 1 
Input
4
0110
0001
0001
1000
3
1 2 4

Output
2
1 4 


-----Note-----

Below you can see the graph from the first example:

[Image]

The given path is passing through vertexes $1$, $2$, $3$, $4$. The sequence $1-2-4$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $1$, $2$ and $4$ in that order is $1-2-3-4$. Note that subsequences $1-4$ and $1-3-4$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $1-3-4$.

In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.

In the fourth example, the paths $1-2-4$ and $1-3-4$ are the shortest paths passing through the vertexes $1$ and $4$.

Difficulty: interview

Starter code:

Solutions:
n = int(input())
INF = 10 ** 18
g = [[INF for i in range(n)] for _ in range(n)]
for i in range(n):
	s = input().rstrip()
	for j in range(n):
		if s[j] == '1':
			g[i][j] = 1
	g[i][i] = 0
for k in range(n):
	for i in range(n):
		for j in range(n):
			g[i][j] = min(g[i][j], g[i][k] + g[k][j])
m = int(input())
p = [int(i) - 1 for i in input().split()]
ptr = 1
ans = [p[0]]
while ptr + 1 < len(p):
	s = ans[-1]
	if g[s][p[ptr]] + 1 != g[s][p[ptr + 1]]:
		ans.append(p[ptr])
	ptr += 1
ans.append(p[-1])
print(len(ans))
for i in ans:
	print(i + 1, end=" ")

import sys
import copy
input = sys.stdin.readline

n=int(input())
EDGE=[list(map(int,list(input().strip()))) for i in range(n)]
m=int(input())
P=list(map(int,input().split()))

Distance=copy.deepcopy(EDGE)

for i in range(n):
    for j in range(n):
        if Distance[i][j]==0 and i!=j:
            Distance[i][j]=float("inf")
        

for k in range(n):# k個までの町を使ってのDisが知れているときに
    for i in range(n):# 町iと
        for j in range(n):# 町jとの最短距離は、
            length=Distance[i][k]+Distance[k][j]
            if Distance[i][j]>length:
                Distance[i][j]=length

ANS=[P[0]]

NOW=0

i=1
while i<m:
    if Distance[P[NOW]-1][P[i]-1]==i-NOW:
        i+=1

    else:
        ANS.append(P[i-1])
        NOW=i-1

ANS.append(P[-1])
print(len(ANS))
print(*ANS)
    



n = int(input())
G = [[] for _ in range(n)]
for i in range(n):
	l = input()
	for j in range(n):
		if l[j] == '1':
			G[i].append(j)

ds = [[-1]*n for _ in range(n)]
for i in range(n):
	ds[i][i] = 0
	l = [i]
	while len(l) > 0:
		l2 = []
		for j in l:
			for k in G[j]:
				if ds[i][k] == -1:
					ds[i][k] = ds[i][j]+1
					l2.append(k)
		l = l2

m = int(input())
p = list(map(int, input().split()))
res = 2
vs = [str(p[0])]
i, j = 0, 1
while j < m:
	if ds[p[i]-1][p[j]-1] < j-i:
		res += 1
		i = j-1
		vs.append(str(p[j-1]))
	j += 1
vs.append(str(p[-1]))
print(res)
print(" ".join(vs))

n = int(input())

nei = []
for _ in range(n):
	s = input()
	nei.append(list(int(c) for c in s))

m = int(input())

p = list([int(x)-1 for x in input().split()])

shortest = []
for i in range(n):
	vals = []
	for j, con in enumerate(nei[i]):
		if i==j:
			vals.append(0)
		elif con:
			vals.append(1)
		else:
			vals.append(10**6)
	shortest.append(vals)

for k in range(n):
	for i in range(n):
		for j in range(n):
			shortest[i][j] = min(shortest[i][j], shortest[i][k] + shortest[k][j])

seq = [p[0]]
dist = 0
for prev, cur in zip(p, p[1:]):
	dist += shortest[prev][cur]
	if shortest[seq[-1]][cur] < dist:
		dist = shortest[prev][cur]
		seq.append(prev)
seq.append(p[-1])

print(len(seq))
print(*[val+1 for val in seq])

import sys
def input():
	return sys.stdin.readline()[:-1]

n = int(input())
s = [input() for _ in range(n)]
d = [[10 ** 30 for _ in range(n)] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if s[i][j] == "1":
			d[i][j] = 1

for k in range(n):
	for i in range(n):
		for j in range(n):
			d[i][j] = min(d[i][j], d[i][k]+d[k][j])

#for i in range(n):
#	print(*d[i])

m = int(input())
p = list(map(int, input().split()))

ans = [p[0]]
cur = 1
while cur < m-1:
	if ans[-1] == p[cur+1]:
		ans.append(p[cur])
	elif d[ans[-1]-1][p[cur]-1] + d[p[cur]-1][p[cur+1]-1] > d[ans[-1]-1][p[cur+1]-1]:
		ans.append(p[cur])
	cur += 1
ans.append(p[-1])

print(len(ans))
print(*ans)

def path(s):
    s1= {s}
    s2 = set()
    used = [0] * (n + 1)
    used[s] = 1
    ans = 0
    while s1:
        ans += 1
        for v in s1:
            for u in graph[v]:
                if used[u] == 0:
                    paths[s][u] = ans
                    used[u] = 1
                    s2.add(u)
        s1 = s2
        s2 = set()


n = int(input())
A = [list(map(int, input())) for _ in range(n)]
graph = {i: set() for i in range(1, n + 1)}
for i in range(n):
    for j in range(n):
        if A[i][j]:
           graph[i + 1].add(j + 1)
m = int(input())
P = list(map(int, input().split()))
paths = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
    path(i)
u = 0
v = P[0]
ans = []
while u < m - 1:
    ans.append(P[u])
    l = u
    r = min(m, u + n + 1)
    while r - l > 1:
        mid = (l + r) // 2
        if paths[P[u]][P[mid]] == mid - u:
            l = mid
        else:
            r = mid
    u = l
ans.append(P[-1])
print(len(ans))
print(*ans)


from collections import deque
N = int(input())
Edge = [list(map(int,input().strip())) for _ in range(N)]

dist = []
inf = 10**9
for i in range(N):
    d = [inf]*N
    d[i] = 0
    Q = deque([i])
    unused = set(range(N))
    unused.remove(i)
    while Q:
        vn = Q.pop()
        for vf in unused.copy():
            if Edge[vn][vf]:
                unused.remove(vf)
                d[vf] = 1 + d[vn]
                Q.appendleft(vf)
    dist.append(d)

M = int(input())
V = tuple([int(x) - 1 for x in input().split()])

Ans = [V[0]]

for v in V[1:]:
    while len(Ans) > 1 and dist[Ans[-2]][Ans[-1]] + dist[Ans[-1]][v] == dist[Ans[-2]][v]:
        Ans.pop()
    Ans.append(v)

Ans = [a+1 for a in Ans]
print(len(Ans))
print(*Ans)


from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())


dis = [[1000000000]*101 for _i in range(101)]

n = int(rd())
for i in range(n+1):
    dis[i][i] = 0

for i in range(1,n+1):
    s = str(rd().strip())
    for j in range(n):
        if s[j] == '1':
            dis[i][j+1] = 1



for k in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(dis[i][j],dis[i][k] + dis[k][j])


m = int(rd())
p = list(rrd())

ans = []

s = 0
pre = 0
l = 0
for i in p:
    if len(ans) == 0:
        s = i
        pre = i
        ans.append(i)
        continue
    if dis[s][i] == l+1:
        pre = i
        l+=1
        continue
    else:
        ans.append(pre)

        s = pre
        pre = i
        l = 1

if s != pre:
    ans.append(pre)

print(len(ans))
print(*ans)

import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
n = int(input())
d = defaultdict(set)
for _ in range(n):
    z = input()
    for i in range(n):
        if z[i] == '1':
            d[_+1].add(i+1)
m = int(input())
z = listin()
ans = [z[0]]
for i in range(1, m-1):
    if z[i] in d[ans[-1]] and z[i+1] in d[z[i]] and z[i+1] not in d[ans[-1]] and ans[-1]!=z[i+1]:
        pass
    else:
        ans.append(z[i])
ans.append(z[-1])
print(len(ans))
print(*ans)

from sys import stdout
import heapq
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      list(map(int, input().split()))
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

def setc2c():
  for c1 in range(n):
    dist = [BIG]*n
    dist[c1] = 0
    hp = [(0,c1)]
    while len(hp)>0:
        curlen,curloc = heapq.heappop(hp)
        if curlen > dist[curloc]:
            continue
        for nxtloc in dst[curloc]:
            newdist = dist[curloc]+1
            if newdist < dist[nxtloc]:
                dist[nxtloc] = newdist
                heapq.heappush(hp, (newdist, nxtloc))
    for c2 in range(n):
        c2c[c1][c2] = dist[c2]

# main

n = inn()
dst = [ [] for i in range(n) ]
c2c = [ [0]*n for i in range(n) ]

for i in range(n):
    s = input()
    for j in range(n):
        if s[j]=='1':
            dst[i].append(j)

m= inn()
p = [x-1 for x in inl()]

setc2c()

v = [p[0]]
curv = p[0]
curi = 0
for i in range(1,m):
    if c2c[curv][p[i]] < i - curi:
        v.append(p[i-1])
        curv = p[i-1]
        curi = i-1

v.append(p[m-1])
k = len(v)
print(k)
for i in range(k):
    printn((' ' if i>0 else '') + str(v[i]+1))
print('')


n=int(input())
d=[]
for i in range(n):
	d+=[[int(i) for i in input()]]
inf=200
for i in range(n):
	for j in range(n):
		if d[i][j]==0 and i!=j:
			d[i][j]=inf
for k in range(n):
	for j in range(n):
		for i in range(n):
			d[i][j]=min(d[i][j],d[i][k]+d[k][j])
m=int(input())
p=list(map(int,input().split()))
path=[p[0]]
j=0
k=0
i=0
while i<=m-1:
	if d[p[j]-1][p[i]-1]==i-j:
		k=i
		i+=1
	elif j!=k:
		path.append(p[k])
		j=k
		i-=1
path.append(p[m-1])
print(len(path))
print(" ".join(map(str,path)))	

n=int(input())
a=[0]
for i in range(n):
    a.append(list(input()))
x=int(input())
b=list(map(int,input().split()))
if x==2:
    print(2)
    print(*b)
    return
st=[b[0]]
st1=[b[0]]
k=b[1]
for i in range(1,n+1):
    a[i][i-1]='1'
    
# print(a)
pr=[]
pr.append(b[0])
# print(,end=" ")
for j in range(2,x):
    for l in st1:
        # print(st,st1,k,b[j])
        if a[l][b[j]-1]=='1':
            st.append(k)
            st=[k]
            st1=[k]
            # print(k,end=" ")
            pr.append(k)
            k=b[j]
            
            break
    else:
        st1.append(b[j])
        k=b[j]
pr.append(b[-1])        
# print(b[-1])    
print(len(pr))
print(*pr)
        
        
        
    


def gns():
    return list(map(int,input().split()))
n=int(input())
mp=[]
for i in range(n):
    mp.append(input())

def bfs(i):
    nxt=[i]
    ans=[None]*n
    ans[i]=0
    v=[False]*n
    v[i]=True
    p=0
    while len(nxt)>0:
        p+=1
        nxt_=[]
        for ni in nxt:
            for nn in range(n):
                if v[nn] or mp[ni][nn]=='0':
                    continue
                v[nn]=True
                ans[nn]=p
                nxt_.append(nn)
        nxt=nxt_
    return ans
dis=[None]*n
for i in range(n):
    dis[i]=bfs(i)
m=int(input())
ms=gns()
ms=[x-1 for x in ms]

ans=[ms[0]]
l=ms[0]
for i in range(1,m-1):
    c=ms[i]
    cn=ms[i+1]
    if dis[l][cn]<=dis[l][c]:
        ans.append(c)
        l=c
ans.append(ms[-1])
ans=[x+1 for x in ans]
print(len(ans))
print(' '.join(map(str,ans)))




n=int(input())
a=[]
for i in range(n):
    a.append(list(map(int,list(input()))))
#print(*a)
m=int(input())
b=list(map(int,input().split()))
for i in range(n):
    for j in range(n):
        if i!=j and a[i][j]==0:
            a[i][j]=10**18
for k in range(n): 
    for i in range(n): 
        for j in range(n): 
            a[i][j] = min(a[i][j] , a[i][k]+ a[k][j]) 
ans=[]
for i in range(m):
    if i==0 or i==m-1:
        ans.append(b[i])
        continue
    x=ans[-1]-1
    if(a[x][b[i]-1]+a[b[i]-1][b[i+1]-1]==a[x][b[i+1]-1]):
        continue
    ans.append(b[i])
print(len(ans))
print(*ans)
#print(*a)


import sys
input = sys.stdin.readline

INF = 10**12
n = int(input())
edge = [[] for _ in range(n)]
for i in range(n):
    line = input().rstrip()
    for j, ch in enumerate(line):
        if i == j:
            edge[i].append(0)
        elif ch == "1":
            edge[i].append(1)
        else:
            edge[i].append(INF)
m = int(input())
a = [int(item) for item in input().split()]

if m == 2:
    print(2)
    print(" ".join([str(item) for item in a]))
    return

for k in range(n):
    for i in range(n):
        for j in range(n):
            edge[i][j] = min(edge[i][j], edge[i][k] + edge[k][j])

# for line in edge:
#     print(line)

frm_id = 0
mid_id = 1
to_id = 2
ans_num = 0
ans = [a[frm_id]]
ans_num += 1
while to_id < len(a):
    frm = a[frm_id] - 1
    mid = a[mid_id] - 1
    to = a[to_id] - 1
    if frm == to or not edge[frm][mid] + edge[mid][to] == edge[frm][to]:
        ans.append(mid + 1)
        ans_num += 1
        frm_id = mid_id 
        to_id += 1
        mid_id += 1
    else:
        to_id += 1
        mid_id += 1
ans.append(to + 1)
ans_num += 1
print(ans_num)
print(" ".join([str(item) for item in ans]))

from collections import deque
n = int(input())
graph = [list([bit == '1' for bit in list(input())]) for _ in range(n)]
m = int(input())
way = list([int(i) - 1 for i in input().split()])
#print(graph)

def dfs(start):
    queue = deque([start])
    d = [-1] * n
    d[start] = 0
    while len(queue) != 0:
        u = queue[0]
        queue.popleft()
        for v in range(n):
            if graph[u][v] and d[v] == -1:
                d[v] = d[u] + 1
                queue.append(v)
    return d


minpath = list(map(dfs, list(range(n))))
good = [way[0]]
checkp = way[0]
for i in range(1, m):
    prev = way[i - 1]
    if minpath[checkp][way[i]] != minpath[checkp][prev] + 1:
        good.append(prev)
        checkp = prev
#print(minpath)
good.append(way[-1])
print(len(good))
print(' '.join([str(p + 1) for p in good]))


def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

n=int(input())
g=[list(input()) for _ in range(n)]
d=[[float('inf')]*n for _ in range(n)]
for i in range(n):
  for j in range(n):
    if g[i][j]=='1':
      d[i][j]=1
warshall_floyd(d)
m=int(input())
arr=list(map(int,input().split()))
for i in range(m):
  arr[i]-=1
ans=[arr[0]]
pos1=0
pos2=1
pos3=2
for i in range(m-2):
  a,b,c=arr[pos1],arr[pos2],arr[pos3]
  if a!=c:
    if d[a][b]+d[b][c]>d[a][c]:
      ans.append(b)
      pos1=pos2
      pos2=pos1+1
      pos3=pos2+1
    else:
      pos2+=1
      pos3+=1
  else:
    if d[a][b]+d[b][c]>=d[a][c]:
      ans.append(b)
      pos1=pos2
      pos2=pos1+1
      pos3=pos2+1
    else:
      pos2+=1
      pos3+=1
ans.append(arr[-1])
l=len(ans)
for i in range(l):
  ans[i]+=1
print(l)
print(*ans)

import sys

n = int(sys.stdin.readline().strip())
A = []
for i in range (0, n):
    A.append(sys.stdin.readline().strip())
D = [[-200 for i in range (0, n)] for j in range (0, n)]
L = []
L2 = []
for i in range (0, n):
    D[i][i] = 0
    L.append([i,i])
for i in range (0, n):
    while len(L) > 0:
        x,y = L.pop()
        for j in range (0, n):
            if A[y][j] == "1" and D[x][j] == -200:
                D[x][j] = i + 1
                L2.append([x,j])
    L = L2[:]
    L2 = []

m = int(sys.stdin.readline().strip())
p = list(map(int,sys.stdin.readline().strip().split()))
k = 1
ans = []
i = 0
j = 1
while j < m-1:
    if D[p[i]-1][p[j+1]-1] == j+1-i:
        j = j + 1
    else:
        ans.append(p[i])
        i = j
        j = j+1
ans.append(p[i])
if i != m-1:
    ans.append(p[m-1])
print(len(ans))
print(" ".join(list(map(str,ans))))



from heapq import heapify, heappush as hpush, heappop as hpop
N = int(input())
X = [[] for _ in range(N)]
for i in range(N):
    s = input()
    for j in range(N):
        if s[j] == "1":
            X[i].append((j, 1))

def dijkstra(n, E, i0=0):
    h = [[0, i0]]
    D = [-1] * n
    done = [0] * n
    D[i0] = 0
    
    while h:
        d, i = hpop(h)
        done[i] = 1
        for j, w in E[i]:
            nd = d + w
            if D[j] < 0 or D[j] >= nd:
                if done[j] == 0:
                    hpush(h, [nd, j])
                    D[j] = nd
    return [d if d >= 0 else 1<<50 for d in D]

Y = []
for i in range(N):
    Y.append(dijkstra(N, X, i))

# print("Y =", Y)

M = int(input())
V = [int(a)-1 for a in input().split()]

a = 0
b = 1
t = Y[V[a]][V[b]]
ANS = [V[a]+1]
while b < M:
    if Y[V[a]][V[b]] < t:
        a = b-1
        ANS.append(V[a]+1)
        t = Y[V[a]][V[b]]
    elif b == M-1:
        break
    else:
        t += Y[V[b]][V[b+1]]
        b += 1
ANS.append(V[M-1]+1)
print(len(ANS))
print(*ANS)



from collections import defaultdict

def bfs(root):
    bool = [False]*(n+1)
    queue = [root]
    bool[root] = True
    level = defaultdict(int)
    level[root] = 0
    while queue:
        z = queue.pop(0)

        for i in hash[z]:
          if bool[i] == False:
              bool[i] = True
              level[i]+=1+level[z]
              queue.append(i)


    return level

hash = defaultdict(list)
n = int(input())

l = []

for i in range(n):
    k = list(input())
    l.append(k)

for i in range(n):
    for j in range(n):
        if l[i][j] == '1':
            hash[i+1].append(j+1)
n1 = int(input())
la = list(map(int,input().split()))

root = la[0]




full = {}

for i in range(1,n+1):
    full[i] = bfs(i)



ans = [la[0]]

j = 0

while j<len(la):

    k = j+1

    while k<len(la):
        # print(k-)
        if full[la[j]][la[k]] == k-j:
           k+=1
        else:
            break



    # break
    if k == j:
        ans.append(la[j])
        j+=1
    else:
        ans.append(la[k-1])
        j=  k-1
        if j == len(la)-1:
            break


print(len(ans))
print(*ans)




''' بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ '''
#codeforces1204C
gi = lambda : list(map(int,input().split()))
n, = gi()
g = [list(map(int, list(input()))) for _ in range(n)]
lenp, = gi()
p = gi()
ans = p[:]
lenans = lenp
k = 1
while k < lenp - 1:
	if g[ans[k - 1] - 1][ans[k + 1] - 1] == 0 and ans[k - 1] != ans[k + 1]:
		p[k] = -1
		ans[k] = ans[k - 1]
		lenans -= 1
		k += 1
	k += 1
print(lenans)
for k in range(lenp):
	if p[k] != -1:
		print(ans[k], end=" ")