1. import java.util.LinkedList; 2. import java.util.Queue; 3. import java.util.Scanner; 4. 5. public class MaxFlow 6. { 7. 8. private int capacity[][]; 9. private int flow[][]; 10. private boolean visited[]; 11. private int pre[]; 12. private int nodes; 13. 14. public MaxFlow( int[][] capacity, int nodes ) 15. { 16. this.capacity = capacity; 17. this.nodes = nodes; 18. this.flow = new int[nodes][nodes]; 19. this.pre = new int[nodes]; 20. this.visited = new boolean[nodes]; 21. } 22. 23. public int maxFlow( int src, int des ) 24. { 25. int maxFlow = 0; 26. 27. for( int i = 0; i < nodes; i++ ) 28. for( int j = 0; j < nodes; j++ ) 29. flow[i][j] = 0; 30. 31. while( true )//find a augment path 32. { 33. for( int i = 0; i < nodes; i++ ) 34. { 35. visited[i] = false; 36. } 37. pre[src] = -1; 38. 39. if(!BFS( src, des )){// the BFS 40. break; 41. } 42. 43. /*DFS(src,des);//DFS 44. if(!visited[des]) 45. break;*/ 46. 47. int increment = Integer.MAX_VALUE; 48. for( int i = des; pre[i] >= src; i = pre[i] ) 49. { 50. //find the min flow of the path 51. increment = Math.min( increment, capacity[pre[i]][i] 52. - flow[pre[i]][i] ); 53. } 54. 55. //update the flow 56. for( int i = des; pre[i] >= src; i = pre[i] ) 57. { 58. flow[pre[i]][i] += increment; 59. flow[i][pre[i]] -= increment; 60. } 61. //increase the maxFow with the increment 62. maxFlow += increment; 63. } 64. return maxFlow; 65. } 66. 67. private void DFS(int src, int des){ 68. visited[src] = true; 69. for(int i = 0; i < nodes; i++){ 70. if(!visited[i] && ( capacity[src][i] - flow[src][i] > 0) ){ 71. pre[i] = src;//record the augment path 72. visited[i] = true; 73. DFS(i,des); 74. } 75. } 76. } 77. 78. private boolean BFS( int src, int des ) 79. { 80. Queue<Integer> queue = new LinkedList<Integer>(); 81. queue.add( src ); 82. visited[src] = true; 83. while( !queue.isEmpty() ) 84. { 85. int node = queue.poll(); 86. for( int i = 0; i < nodes; i++ ) 87. { 88. if( !visited[i] && (capacity[node][i] - flow[node][i] > 0) ) 89. { 90. queue.add( i ); 91. visited[i] = true; 92. pre[i] = node;//record the augment path 93. } 94. } 95. } 96. 97. return visited[des]; 98. } 99. 100. public static void main( String[] args ) 101. { 102. 103. int nodes, edges; 104. Scanner scanner = new Scanner( System.in ); 105. 106. nodes = scanner.nextInt(); 107. edges = scanner.nextInt(); 108. 109. int[][] capacity = new int[nodes][nodes]; 110. 111. int src, des, c; 112. for( int i = 0; i < edges; i++ ) 113. { 114. src = scanner.nextInt(); 115. des = scanner.nextInt(); 116. c = scanner.nextInt(); 117. capacity[src][des] = c; 118. } 119. 120. MaxFlow maxFlow = new MaxFlow( capacity, nodes ); 121. System.out.println( maxFlow.maxFlow( 0, nodes - 1 ) ); 122. } 123. }
[max-flow]ford-fulkerson algorithm (转)
最新推荐文章于 2024-10-13 08:00:00 发布