Another Contest 1 Problem 2 - Graphs

View as PDF

Submit solution

Points: 15
Time limit: 0.6s
Memory limit: 256M

Problem type
Allowed languages
Ada, Assembly, Awk, Brain****, C, C#, C++, COBOL, CommonLisp, D, Dart, F#, Forth, Fortran, Go, Groovy, Haskell, Intercal, Java, JS, Kotlin, Lisp, Lua, Nim, ObjC, OCaml, Octave, Pascal, Perl, PHP, Pike, Prolog, Python, Racket, Ruby, Rust, Scala, Scheme, Sed, Swift, TCL, Text, Turing, VB, Zig

This problem has a simple statement.

Given an undirected, unweighted graph of N vertices and M edges, and Q pairs of vertices, compute the distance between each pair of vertices.

We ran out of time trying to set strong test data for the problem though, so we did it randomly. Here's how we generated our test data.

  • We picked values for N, M, and Q. The vertices are numbered from 1 to N.
  • We generated, uniformly at random, a pair of distinct integers between 1 and N and added an edge between those vertices as long as they weren't already directly connected by an edge. This means the graph has no self-loops, nor parallel edges.
  • The above step was repeated until the graph contains exactly M edges.
  • We generated, uniformly at random, Q pairs of integers between 1 and N for the queries.


N = 10^5, M = 2 \cdot 10^5, and Q = 10^4.

Note: The sample does not respect the constraints. Your solution does not need to produce the correct output on the sample to get AC.

Input Specification

The first line of input contains three positive integers, N, M, and Q.

The next M lines each contain two distinct positive integers from 1 to N, representing an edge between the two given vertices.

The next Q lines each contain two positive integers from 1 to N, representing a distance query between the two given vertices.

Output Specification

Output Q lines. For each distance query, output -1 if the two vertices are disconnected, otherwise output the distance between the two vertices. Output answers for the queries in the order they're given, one query per line.

Sample Input

3 2 2
1 2
2 3
1 3
2 3

Sample Output



  • -1
    349081547  commented on Sept. 14, 2019, 7:01 p.m. edited

    I literally just started c++. Is there something wrong with my program?? It says the compiler output is too long.

    • 17
      xiaowuc1  commented on Sept. 14, 2019, 7:13 p.m.

      Your code does not compile. You should compile your code on your machine before submitting it - if the compiler output is too long, that usually means you have too many compiler errors. If your code does compile, it will automatically be run on the test cases.

      If you can't compile locally for some reason, you can use a service like If you click on the link in the previous sentence, you can see the compiler errors for your program. You should fix the first errors before looking at the later ones.

      • 0
        349081547  commented on Oct. 26, 2019, 10:13 a.m.