Computer >> Máy Tính >  >> Lập trình >> C ++

Chương trình C ++ để triển khai thuật toán Edmonds-Karp

Đây là chương trình C ++ để triển khai thuật toán Edmonds-Karp để tính toán lưu lượng tối đa giữa đỉnh nguồn và đỉnh chìm.

Thuật toán:

 Begin function edmondsKarp ():khởi tạo luồng bằng 0. Nếu có một đường dẫn tăng cường từ nguồn đến phần chìm, hãy thêm đường dẫn vào luồng. Dòng trả về.End 

Mã mẫu

 #include  #include  #include  #include  #include  using namespace std; int c [10] [10]; int flowPassed [10] [10]; vector  g [10]; int parList [10]; int currentPathC [10]; int bfs (int sNode, int eNode) // tìm kiếm đầu tiên theo chiều rộng {memset (parList, -1, sizeof (parList)); memset (currentPathC, 0, sizeof (currentPathC)); queue  q; // khai báo vector queue q.push (sNode); parList [sNode] =-1; // khởi tạo nút nguồn của parlist currentPathC [sNode] =999; // khởi tạo nút nguồn của currentpath while (! q.empty ()) // nếu q không trống {int currNode =q.front (); q.pop (); for (int i =0; i  0) {parList [to] =currNode; currentPathC [to] =min (currentPathC [currNode], c [currNode] [to] - flowPassed [currNode] [to]); if (to ==eNode) {return currentPathC [eNode]; } q.push (to); }}}} return 0;} int edmondsKarp (int sNode, int eNode) {int maxFlow =0; while (true) {int flow =bfs (sNode, eNode); if (flow ==0) {break; } maxFlow + =flow; int currNode =eNode; while (currNode! =sNode) {int prevNode =parList [currNode]; flowPassed [prevNode] [currNode] + =flow; flowPassed [currNode] [presNode] - =flow; currNode =presNode; }} return maxFlow;} int main () {int gật đầu, edCount; cout <<"nhập số nút và số cạnh \ n"; cin>> gật đầu>> edCount; nguồn int, chìm; cout <<"vào nguồn và chìm \ n"; cin>> nguồn>> chìm; for (int ed =0; ed > from>> to>> cap; c [from] [to] =cap; g [from] .push_back (to); g [to] .push_back (from); } int maxFlow =edmondsKarp (nguồn, chìm); cout < 

Đầu ra

 nhập số lượng các nút và cạnh đỉnh cùng với dung lượng