EaglePB2's Competitive Programming Writeups
  • Home Page
  • Why Python?
  • Why 10^9 + 7?
  • General Formatting Title
  • 🇲🇾CodeNection
    • 2021
      • Closed Cateogry
        • Attend Talks
        • Distant Relatives
        • Concert
        • Mamak
        • Fair Contest
      • Open Preliminary Round
        • f(Aibohphobia)^-1
        • Did they cheat?
        • Semester Breaks
      • Open Final Round
        • Ways 1
        • Circular Campus
        • A joke
        • 🥰Last year when life was better
        • Thank You Pizza
    • 2023
      • Test Round
        • Codey and Alphabetical Scoring
        • Codey and Binary Guesser
      • Preliminary Round
        • Codey and CodeNection
        • Codey and Hide-and-Seek
        • Codey and Math
        • Codey and Textbooks
        • Codey and Money
        • Codey and Team Selection
        • Codey and Painted Tree
        • Codey and Number Grid
        • Codey and Crimes
      • Final Round
        • Codey and CodeNection 2
        • Codey and Connection
        • Codey and Schedule
        • Codey and School Supplies
        • Codey and Zombies
        • Codey and Sightseeing
        • Codey and Apples
        • Codey and Facto
        • Codey and Zoey
    • 2024
      • Test Round
        • Codey and Sunday
        • Codey and Takoyaki
      • Preliminary Round
        • Codey and CodeNection
        • Codey and Pebbles
        • Codey and Spam
        • Codey and Coins
        • Codey and Rectangles
        • Codey and Manuscript
        • Codey and Recipes
        • Codey and Toy Kingdom
        • Codey and Peaks
      • Final Round
        • Codey and Exit
        • Codey and Gardening
        • Codey and Symbol
        • Codey and Rectangles 2
        • Codey and Jutsu
        • Codey and Toy Kingdom 2
        • Codey and Speeches
  • ABaKoDa
    • 2023
      • Round 1
        • Problem Letters
        • Problem Statistics
        • Rankings Order
        • Rankings Search
      • Round 2
        • Abakoda Letters
        • Borrowed Words
        • Kensorship
        • Duel Languages
  • Meta Coding Competitions
    • 2011
      • Qualification Round
        • Double Squares
        • Peg Game
        • Studious Student
      • Round 1A
        • Diversity Number
        • Turn on the Lights
        • Wine Tasting
      • Round 1B
        • Chess 2
        • Diminishing Circle
        • Slot Machine Hacker
      • Round 1C
        • N-Factorful
        • Polynomial Factoring
        • Risky Slide
      • Round 2
        • Bonus Assignments
        • Scott's New Trick
        • Studious Student II
      • Final Round
        • Alien Game
        • Party Time
        • Safest Place
  • EaglePB2's Special
    • Hong Kong Identity card
    • Cycle Prefix Averages
    • Word Squares
Powered by GitBook
On this page
  • Question
  • Input Format
  • Constraints
  • Output Format
  • Sample Inputs:
  1. CodeNection
  2. 2023
  3. Final Round

Codey and Sightseeing

https://www.hackerrank.com/contests/codenection-2023-final-round-open-category/challenges/cn-c15/

PreviousCodey and ZombiesNextCodey and Apples

Last updated 2 months ago

Question

Codey has an adventurous spirit. Whatever catches its eye, it will take a look at. There are n locations, m roads, and k of the locations that have attracted Codey's attention. Each road represents a distance of 1. You will be given an array a of length k, where aia_iai​represents the iii-th place of interest.

Due to its curiosity, Codey is eager to find the shortest distance it needs to take to reach the closest place of interest from each location. Your task is to find the sum of distances from every location to its closest place of interest.

Input Format

The first line contains three integers, n, m and k, where n represents the total number of locations, m represents the number of roads and k represents the number of places of interest.

The second line contains k integers a1,a2,...aka_1, a_2, ... a_ka1​,a2​,...ak​ , each representing the iii-th place of interest.

The following m lines contains two integers, u and v, which indicates the road between location u and v.

Constraints

1≤n≤1051 \le n \le 10^51≤n≤105
n−1≤m≤n∗n−12n - 1 \le m \le n *\frac{n-1}{2}n−1≤m≤n∗2n−1​
  • It is guaranteed that there is no self loop & multiple edges for each test case

Output Format

Output an integer representing the sum of distances from every location to its closest place of interest.

Sample Inputs:

Input

3 2 1
1 
2 3
2 1

Output

3

Explanation

There is a total distance of 3 from each location to the place of interest as follows:

For location 1, the closest place of interest is itself, therefore distance is 0.

For location 1, the closest place of interest is location 1, therefore distance is 1.

For location 3, the closest place of interest is location 1, therefore distance is 2.


Solution - Dijkstra Algorithm

This is a classic Dijkstra Algorithm question, which is to find the shortest distance to the destination and finally add it up.

If you know Dijkstra Algorithm, this should be easy, otherwise, don't waste your time onto here and you should skip to the next question, unless this is your final question to solve.

Here's the solution:

import heapq

def dijkstra(n, graph, sources):
    distances = [float('inf')] * n
    pq = []
    
    for source in sources:
        distances[source] = 0
        heapq.heappush(pq, (0, source))
    
    while pq:
        current_dist, current_node = heapq.heappop(pq)
        
        if current_dist > distances[current_node]:
            continue
        
        for neighbor in graph[current_node]:
            new_dist = current_dist + 1
            if new_dist < distances[neighbor]:
                distances[neighbor] = new_dist
                heapq.heappush(pq, (new_dist, neighbor))
    
    return distances

def sum_of_distances(n, m, k, places_of_interest, roads):
    graph = [[] for _ in range(n)]
    
    for u, v in roads:
        graph[u].append(v)
        graph[v].append(u)
    
    distances = dijkstra(n, graph, places_of_interest)
    
    return sum(distances)

n, m, k = map(int, input().strip().split())
places_of_interest = list(map(int, input().strip().split()))
places_of_interest = [p - 1 for p in places_of_interest]

roads = []
for _ in range(m):
    u, v = map(int, input().strip().split())
    roads.append((u - 1, v - 1))

print(sum_of_distances(n, m, k, places_of_interest, roads))

Note that I used heapq library to create heap structure. If you are going for data structure based questions (paths, trees, etc), this would be your most important library to go.

1≤k≤n1 \le k \le n1≤k≤n
1≤ai≤n1 \le a_i \le n1≤ai​≤n

All aia_iai​ are unique

Therefore, the sum of distances from each location to its closest place of interest is 0+1+2=30 + 1 + 2 = 30+1+2=3.

🇲🇾