Skip to content
Programmingoneonone - Logo
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Computer System Architecture
    • Microprocessor
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
      • Data Structures Solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone - Logo
Programmingoneonone

HackerEarth Just shortest distance problem solution

YASH PAL, 31 July 202416 February 2026
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 HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy
  • DMCA

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes