Unique paths
Practice
5 (1 votes)
Problem
69% Success 246 Attempts 30 Points 1s Time Limit 256MB Memory 1024 KB Max Code

You are given a connected undirected graph containing \(N\) nodes and \(M\) edges. The task is very simple. You are provided two nodes \(u\) and \(v\). You are required to check whether the path from \(u\) to \(v\) is unique or not. If there exists a path, you are required to determine the distance between the nodes \(u\) and \(v\), then print \(-1\). You must perform these operations for \(Q\) queries. 

Input format

  • First line: Two space-separated integers\(N\) and \(M\) 
  • Next \(M\) lines: Two space-separated integers \(u\) and \(v\) denoting that there is an edge between node \(u\) and \(v\)
  • Next line contains a single integer \(Q\)  denoting the number of queries
  • Next \(Q\) lines: Two space-separated integers \(u\) and \(v\)

Output format

For each query, print the distance between the two nodes if there exists a unique path between the nodes in that query. Otherwise, print \(-1\).

Constraints

\(2 \le N \le 10^5\\ N - 1 \le M \le min(10^5, \frac{N * (N - 1)}{2})\\ 1 \le u, v \le N$$\\ 1 \le Q \le 10^5\)

The provided graph is connected and it does not contain self-loops and multiple edges.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
90 votes
Tags:
ArraysBrute-force searchData StructuresEasyHash TablesImplementationMathOne-dimensional
Points:30
13 votes
Tags:
AlgorithmsApprovedDynamic ProgrammingEasy
Points:30
187 votes
Tags:
Ad-HocAlgorithmsApprovedDynamic ProgrammingMediumOpen
Editorial

Login to unlock the editorial