This is an old classic problems which need you design an algorithm
whose running time is O(n) or nearly O(n) (e.g. O(n*ack-1(n)), where 
n is dimensions of input file. To achieve this you must treat with a
whole segment, that is, regard a segment as a vertex and make an edge 
between two vertices if they are connected together. As I know, there
are two ways to implement it:

1. Build the graph and find its connected components.
This algorithm can be implemented in O(n) by using stantard algorithm.
But it has two disadvantages:
  - It can work when you have already know all the information of the
    input file, i.e., it's an offline algorithm, if you have read 
    first 3 lines of the input file only, you cannot tell the how 
    many connected componts then.
  - It requires much space the restore the graph. When the memory 
    limit is strict, it will embarrass you.   
Since above let us see an algorithm which may be used more widely.

2. Use a disjoint-set to maintain the connected components with a set
represents a connect components. As we know, disjoint-set can be 
implemented in O(ack-1(n)) time each operation. The time complexity
of this algorithm is O(nack-1(n)), but this algorithm will make you
able to answer while you are reading the input file and will cost you
less memory.

My program uses this algorithm.