Challenge: The Road That Makes a Loop
Completed
Roads are built one by one between n towns. Print the first road (a b) that joins two towns that were already connected, or no loop.
Input
Line 1: n m. Then m lines a b in build order.
Output
a b or no loop.
Example
Input
4 4 0 1 1 2 2 0 2 3
Output
2 0
Editor
C++
Hints
Before joining, check whether find(a) == find(b).
Keep reading all roads even after finding the answer.
Solution explanation
Union-find answers “already connected?” as roads are added.
Show solution
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
vector<int> parent;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
int main() {
int n, m;
cin >> n >> m;
parent.resize(n);
iota(parent.begin(), parent.end(), 0);
int ansA = -1, ansB = -1;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
int ra = find(a), rb = find(b);
if (ra == rb) {
if (ansA == -1) { ansA = a; ansB = b; }
} else {
parent[rb] = ra;
}
}
if (ansA == -1) cout << "no loop" << endl;
else cout << ansA << " " << ansB << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module