Pagini recente » Cod sursa (job #781668) | Cod sursa (job #260048) | Cod sursa (job #237943) | Cod sursa (job #1565981) | Cod sursa (job #885792)
Cod sursa(job #885792)
#include <stdio.h>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
const int sz = 351;
const int infinity = 0x3f3f3f3f;
bool BellmanFord();
FILE *in,*out;
bool visited[sz];
int nodes, edges, source, destination;
int cost[sz][sz];
int capacity[sz][sz];
int dist[sz];
int father[sz];
int maxFlowMinCost;
int cFlow[sz][sz];
vector<int> graph[sz];
int main()
{
in=fopen("fmcm.in","rt");
out=fopen("fmcm.out","wt");
fscanf(in,"%d%d%d%d",&nodes, &edges, &source, &destination);
int rFrom, rTo, flow, rCost;
for(int i=1; i<=edges; ++i)
{
fscanf(in,"%d%d%d%d", &rFrom, &rTo, &flow, &rCost);
cost[rFrom][rTo] = rCost;
cost[rTo][rFrom] = -rCost;
capacity[rFrom][rTo] = flow;
graph[rFrom].push_back(rTo);
graph[rTo].push_back(rFrom);
}
while(BellmanFord())
{
int node;
int minFlow = infinity;
for(node=destination; node!=source; node=father[node])
minFlow = min(minFlow, capacity[father[node]][node] - cFlow[father[node]][node]);
if(minFlow)
for(node=destination; node!=source; node=father[node])
{
cFlow[father[node]][node] += minFlow;
cFlow[node][father[node]] -= minFlow;
}
maxFlowMinCost += minFlow * dist[destination];
}
fprintf(out,"%d",maxFlowMinCost);
fclose(in);
fclose(out);
return 0;
}
bool BellmanFord()
{
memset(visited, false, sizeof(visited));
visited[source] = true;
memset(dist, infinity, sizeof(dist));
dist[source] = 0;
queue<int> myQ;
myQ.push(source);
while(!myQ.empty())
{
int node = myQ.front();
myQ.pop();
vector<int>::iterator it, end = graph[node].end();
for(it=graph[node].begin(); it!=end; ++it)
if(capacity[node][*it] != cFlow[node][*it] && dist[node] + cost[node][*it] < dist[*it])
{
dist[*it] = dist[node] + cost[node][*it];
father[*it] = node;
if(!visited[*it])
{
myQ.push(*it);
visited[*it] = true;
}
}
visited[node] = false;
}
if(dist[destination] != infinity)
return true;
else return false;
}