Using an adjacency list like representation to store numbers that lead to same remainder .
Vector < Vector < Integer > > v = new Vector < Vector < Integer > > ( m ) ; for ( int i = 0 ; i < m ; i ++ ) v . add ( new Vector < Integer > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) {