Given a graph with N vertices numbered 1 to N and M edges, the task is to find the max flow from vertex 1 to vertex N.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. The first line of each test case contains two space separated integers N and M . Then in the next line are M space separated triplets x, y, z denoting an undirected edge from x to y with a flow capacity of z.
Output:
For each test case in a new line print a single integer denoting the maximum flow between 1 to N.
Constraints:
1<=T<=100
1<=N,M<=1000
Example:
Input:
2
5 4
1 2 1 3 2 2 4 2 3 2 5 5
4 4
1 2 8 1 3 10 2 4 2 3 4 3
Output:
1
5
classSolution {staticint totalFlow;// The input is adjacency matrix graph// It does not matter whether the input is directed or undirected// If it is undirected just assume 1 flow as back flow of otherpublicstaticintmaxFlow(int[][] graph) { totalFlow =0;while (BFS(graph,0,graph.length-1)) {// Nothing to do here }return totalFlow; }publicstaticbooleanBFS(int[][] graph,int source,int target) {boolean[] visited =newboolean[graph.length];int[] parent =newint[graph.length];for (int i =0; i <graph.length; i++) parent[i] = i;Queue<Integer> q =newLinkedList<>(); visited[source] =true;boolean isReachable =false;q.add(source);while (q.size() !=0) {int node =q.poll();if (node == target) { isReachable =true;break; }// Now we will go through all the neighbors and add// neighbors with edge flow > 0 && !visitedfor (int i =0; i <graph.length; i++) {if (graph[node][i] >0&&!visited[i]) { visited[i] =true;q.add(i); parent[i] = node; } } }if (isReachable) {// Finding the min flow in the path from source to targetint minFlow =Integer.MAX_VALUE;int node = target;while (node != parent[node]) { minFlow =Math.min(minFlow, graph[parent[node]][node]); node = parent[node]; }// Now we need to add this flow to our answer// aswell as remove it from original flow and add to to back flow totalFlow += minFlow; node = target;while (node != parent[node]) { graph[parent[node]][node] -= minFlow; graph[node][parent[node]] += minFlow; node = parent[node]; } }return isReachable; }}