Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- typedef pair<int, int> PAIR;
- class Graph
- {
- int V,N,m;
- list< pair<int, int> > *adj;
- public:
- Graph(int V,int m)
- {
- this->V = V;
- this->m = m;
- adj = new list<PAIR> [V];
- }
- void setnVertices(int n)
- {
- this->V = V;
- }
- void addEdge(int u, int v, int w)
- {
- adj[u].push_back(make_pair(v, w));
- //adj[v].push_back(make_pair(u, w));
- }
- bool isEdge(int u,int v)
- {
- for(auto it = adj[u].begin(); it!=adj[u].end(); it++)
- {
- if((*it).first == v)
- {
- return true;
- }
- }
- return false;
- }
- int getWeight(int u,int v)
- {
- for(auto it = adj[u].begin(); it!=adj[u].end(); it++)
- {
- if((*it).first == v)
- {
- return (*it).second;
- }
- }
- return 10001;
- }
- bool bfs(int rGraph[V][V], int s, int t, int parent[])
- {
- bool visited[V];
- memset(visited, 0, sizeof(visited));
- queue <int> q;
- q.push(s);
- visited[s] = true;
- parent[s] = -1;
- while (!q.empty())
- {
- int u = q.front();
- q.pop();
- for (int v=0; v<V; v++)
- {
- if (visited[v]==false && rGraph[u][v] > 0)
- {
- q.push(v);
- parent[v] = u;
- visited[v] = true;
- }
- }
- }
- return (visited[t] == true);
- }
- int fordFulkerson(int graph[V][V], int s, int t)
- {
- int u, v;
- int rGraph[V][V];
- int flow[V][V];
- for (u = 0; u < V; u++)
- for (v = 0; v < V; v++)
- {
- rGraph[u][v] = graph[u][v];
- flow[u][v] = 0;
- }
- int parent[V];
- int max_flow = 0;
- while (bfs(rGraph, s, t, parent))
- {
- int path_flow = INT_MAX;
- for (v=t; v!=s; v=parent[v])
- {
- u = parent[v];
- path_flow = min(path_flow, rGraph[u][v]);
- }
- for (v=t; v != s; v=parent[v])
- {
- u = parent[v];
- rGraph[u][v] -= path_flow;
- rGraph[v][u] += path_flow;
- flow[u][v] += path_flow;
- }
- max_flow += path_flow;
- }
- for(int i = 0; i < V; i++)
- {
- for(int j = 0; j < V; j++)
- {
- if(graph[i][j]!=0)
- {
- cout<<i<<" "<<j<<" "<<flow[i][j]<<"/"<<graph[i][j]<<endl;
- }
- }
- }
- return max_flow;
- }
- }; /// END OF GRAPH CLASS
- int main()
- {
- int N,M;
- cin>>N>>M;
- int graph[N][N];
- Graph g(N,M);
- g.setnVertices(N);
- for(int i = 0; i<M; i++)
- {
- cin>>u>>v>>w;
- g.addEdge(u,v,w);
- graph[u][v] = w;
- }
- cout << "The maximum possible flow is " <<g.fordFulkerson(graph, 0, 5);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement