I am getting TLE for following problem : http://www.spoj.com/problems/MATCHING/ . I have used Hopcroft–Karp algorithm :
import java.util.*;
public class MatchingHK{
static int N;
static int M;
static int P;
static int pairU[];
static int pairV[];
static int dist[];
static int NIL = 0;
static int INF = Integer.MAX_VALUE;
static ArrayList<Integer> adj[];
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
P = sc.nextInt();
pairU = new int[N+1];
pairV = new int[M+1];
dist = new int[N+1];
adj = new ArrayList[N+1];
for(int i = 1;i <= N;i++){
adj[i] = new ArrayList<Integer>();
}
for(int i = 0;i < P;i++){
int c = sc.nextInt();
int b = sc.nextInt();
adj[c].add(b);
}
System.out.println(maxMatching());
}
public static int maxMatching(){
int result = 0;
while(bfs()){
for(int i = 1;i <= N;i++){
if(pairU[i] == NIL && dfs(i)){
result++;
}
}
}
return result;
}
public static boolean bfs(){
PriorityQueue<Integer> q = new PriorityQueue<Integer>();
for(int i = 1;i <= N;i++){
if(pairU[i] == NIL){
dist[i] = 0;
q.add(i);
}
else{
dist[i] = INF;
}
}
dist[NIL] = INF;
while(!q.isEmpty()){
int u = q.poll();
if(dist[u] < dist[NIL]){
for(int v : adj[u]){
if(dist[pairV[v]] == INF){
dist[pairV[v]] = dist[u] + 1;
q.offer(pairV[v]);
}
}
}
}
return (dist[NIL] != INF);
}
public static boolean dfs(int u){
if(u != NIL){
for(int v : adj[u]){
if(dist[pairV[v]] == (dist[u]+1) && dfs(pairV[v])){
pairV[v] = u;
pairU[u] = v;
return true;
}
}
dist[u] = INF;
return false;
}
return true;
}
}
Is my implementation of Hopcroft Karp algorithm wrong or do I need to use different algorithm for above problem?