Converting Bipartite Matching to Max Flow Algorithm
//This is conversion from Bipartite matching to Max-FLow algorithm.
//Nice way to convert.
//I have used EdmondsKarp algorithm for the conversion.
class PointyWizardHats {
public:
int graph[205][205],lnode,rnode,parent[205],visited[200],city;
bool bfs(int s,int t)
{
parent[s]=-1;
visited[s]=true;
queue<int> Q;
Q.push(s);
while(!Q.empty())
{
int u=Q.front();
Q.pop();
if(u==t)
return true;
for(int v=0;v<city;v++)
{
if(!visited[v] and graph[u][v]>0)
{
Q.push(v);
visited[v]=true;
parent[v]=u;
}
}
}
return false;
}
int maxflow(int s,int t)
{
int mflow=0;
CLR(visited);
CLR(parent);
while(bfs(s,t))
{
CLR(visited);
int v,u;
int mi=10000000;
for(v=t;v!=s;v=parent[v]){u=parent[v];
mi=min(mi,graph[u][v]);}
for(v=t;v!=s;v=parent[v])
{
u=parent[v];graph[u][v]-=mi;graph[v][u]+=mi;
}
mflow+=mi;
}
return mflow;
}
bool can_be_kept(int bh,int br,int th,int tr) // General Constraint for the problem
{
if(br>tr and (th*br>bh*tr))
return true;
return false;
}
int getNumHats(vector <int> topHeight, vector <int> topRadius, vector <int> bottomHeight, vector <int> bottomRadius)
{
CLR(graph);
lnode=bottomHeight.size();
rnode=topHeight.size();
for(int i=0;i<lnode;i++)
graph[0][i+1]=1; //Where 0 is the source it connects to all the u nodes .
for(int i=0;i<lnode;i++) //Now take all the u nodes starting from 1 to lnode-
for(int j=0;j<rnode;j++)
if(can_be_kept(bottomHeight[i],bottomRadius[i],topHeight[j],topRadius[j]))
graph[i+1][lnode+j+1]=1;
for(int i=0;i<rnode;i++)
graph[lnode+i+1][rnode+1+lnode]=1;
city=rnode+lnode+2;
return maxflow(0,rnode+1+lnode);
}
};
No comments:
Post a Comment