Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • 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
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerEarth Root paths problem solution

YASH PAL, 31 July 202416 February 2026
In this HackerEarth Root paths problem solution Alice and Bob play a game. The game starts with a graph that contains n nodes and no edges. You are required to process q queries of two types:
 
Add a directed edge from u[i] to v[i].
Print x[i] if there is a directed path from vertex 1 to vertex x[i]. Otherwise, print 0.
 
 
HackerEarth Root paths problem solution

 

 

HackerEarth Root paths problem solution.

#include <iostream>
#include <vector>

using namespace std;

class Solver {
public:

int n, q, t;
Solver(int nn) {
n = nn;
color.resize(n + 1);
G.resize(n + 1);
color[1] = 1;

}

vector <int> color;
vector <vector<int> > G;

inline void repaint(int x) {
while (!G[x].empty()) {
int to = G[x].back();
G[x].pop_back();

if (color[to]) {
continue;
} else {
color[to] = 1;
repaint(to);
}
}
}

inline void add_edge(int u, int v) {
if (color[v]) {
return;
}
if (color[u]) {
color[v] = 1;
repaint(v);
} else {
G[u].push_back(v);
}
}

inline int get_ans(int x) {
if (color[x]) {
return x;
}
return 0;
}

};
int main() {

ios_base::sync_with_stdio(false);
cin.tie(0);
int n, q, t;
cin >> n >> q >> t;

Solver *s = new Solver(n);
int lastans = 0;
for (int i = 1; i <= q; i++) {
int type;
cin >> type;
if (type == 1) {
int a, b;
cin >> a >> b;
a = (a ^ (t * lastans)) % n + 1;
b = (b ^ (t * lastans)) % n + 1;
s->add_edge(a, b);
} else {
int a;
cin >> a;
a = (a ^ (t * lastans)) % n + 1;
lastans = s->get_ans(a);
cout << lastans << 'n';
}
}

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

Practice

  • Java
  • C++
  • C

Follow US

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