18/03: Problem D
This commit is contained in:
parent
59bcdd0401
commit
dda8fdf3fa
54
18-03-24/d.py
Normal file
54
18-03-24/d.py
Normal file
@ -0,0 +1,54 @@
|
||||
def main():
|
||||
n, m, k = map(int, input().split())
|
||||
a = [int(i) for i in input().split()]
|
||||
# roads = [list(map(int, input().split())) for _ in range(m)]
|
||||
|
||||
voisins = {i:set() for i in range(1, n+1)}
|
||||
|
||||
A = set(a) # pour les test d'appartenance
|
||||
special = False
|
||||
for _ in range(m):
|
||||
x, y = map(int, input().split())
|
||||
voisins[x].add(y)
|
||||
voisins[y].add(x)
|
||||
if not special and (x in A and y in A):
|
||||
special = True
|
||||
|
||||
|
||||
def distance(source, dist):
|
||||
"""calculer la distance d'un sommet à tous les autres"""
|
||||
non_vus = set((i+1 for i in range(n) if i+1 != source))
|
||||
queue = [source]
|
||||
dist[source] = 0
|
||||
while queue != []:
|
||||
nextQ = []
|
||||
while queue != []:
|
||||
s = queue.pop()
|
||||
for v in voisins[s]:
|
||||
if v in non_vus:
|
||||
non_vus.remove(v)
|
||||
nextQ.append(v)
|
||||
dist[v] = dist[s]+1
|
||||
queue = nextQ
|
||||
|
||||
dist_n = [0 for _ in range(n+1)]
|
||||
dist_1 = [0 for _ in range(n+1)]
|
||||
distance(n, dist_n)
|
||||
distance(1, dist_1)
|
||||
|
||||
if special:
|
||||
return dist_n[1] # On ne rajoute rien
|
||||
|
||||
# On regarde lequel ajouter
|
||||
a.sort(key=lambda x: dist_1[x]-dist_n[x])
|
||||
sp_count = len(a)
|
||||
b = [dist_n[a[-1]] for i in range(sp_count)]
|
||||
for sp in range(1, sp_count):
|
||||
b[sp_count-1-sp] = max(b[sp_count-sp], dist_n[a[sp_count-sp]])
|
||||
|
||||
return min(
|
||||
dist_1[n],
|
||||
max((dist_1[a[i]]+b[i] for i in range(0, len(a)-1)))+1
|
||||
)
|
||||
|
||||
print(main())
|
Loading…
Reference in New Issue
Block a user