Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

HackerEarth Just shortest distance problem solution

YASH PAL, 31 July 2024
In this HackerEarth Just shortest distance problem solution You are given an empty graph of N vertices and M queries of two types:
  1. Given a number X answer what is the shortest distance from the vertex 1 to the vertex X.
  2. Given two integers X, Y add the new oriented edge from X to Y.
HackerEarth Just shortest distance problem solution

HackerEarth Just shortest distance problem solution.

#include<bits/stdc++.h>

const int N = 1050;

using namespace std;

int n, m;
int dist[N];
vector<int> g[N];

void update(int v)
{
for (int i = 0; i < g[v].size(); i++)
{
int to = g[v][i];
if (dist[to]>dist[v] + 1)
{
dist[to] = dist[v] + 1;
update(to);
}
}
}


int main(){
ios_base::sync_with_stdio(0);

cin >> n >> m;

for (int i = 2; i <= n; i++)
dist[i] = 1e9;

for (int i = 1; i <= m; i++)
{
int tp;
cin >> tp;

if (tp == 1)
{
int x;
cin >> x;
if (dist[x] > 1e8)
cout << -1 << endl;
else
cout << dist[x] << endl;
}
if (tp == 2)
{
int a, b;
cin >> a >> b;
g[a].push_back(b);
if (dist[b] > dist[a] + 1)
{
dist[b] = dist[a] + 1;
update(b);
}
}
}

return 0;
}
coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes