Cod sursa(job #285112)

Utilizator ScrazyRobert Szasz Scrazy Data 22 martie 2009 13:03:04
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn = 360;

#define pb push_back
#define inf 0x3f3f3f3f

int n, m; 

int f[maxn][maxn], c[maxn][maxn], cost[maxn][maxn];
int d[maxn], inq[maxn];
vector<int> g[maxn];

int maxflow = 0;

int sout, din; 

int ok;

int p[maxn], viz[maxn];

void read()
{
    scanf("%d%d%d%d", &n, &m, &sout, &din);

    for (int i = 0; i < m; ++i)
    {
	int x, y, cc, costc;
	scanf("%d%d%d%d", &x, &y, &cc, &costc);

	g[x].pb(y); g[y].pb(x);
	c[x][y] += cc;
	cost[x][y] = costc;
	cost[y][x] = -costc;
    }
} 

int bf()
{ 
    memset(d, 0x3f, sizeof(d));
    memset(inq, 0, sizeof(inq));
    memset(p, 0, sizeof(p));

    queue<int> Q;
    Q.push(sout); d[sout] = 0; 
    inq[sout] = 1;

    while (!Q.empty())
    {
	int akt = Q.front();
	Q.pop(); 

	for (int i = 0; i < g[akt].size(); ++i)
	{
	    int next = g[akt][i];
	    if (c[akt][next] - f[akt][next] == 0) continue;
	    if (d[next] > d[akt] + cost[akt][next])
	    {
		d[next] = d[akt] + cost[akt][next];
		p[next] = akt;
		if (!inq[next])
		{
		    Q.push(next);
		    inq[next] = 1;
		}
	    }
	} 
	inq[akt] = 0;
    }

    if (d[din] != inf)
    {
	ok = 1;
	int minn = inf;
	for (int i = din; i != sout; i = p[i])
	    minn = min(c[p[i]][i] - f[p[i]][i], minn);
	for (int i = din; i != sout; i = p[i])
	{
	    f[p[i]][i] += minn;
	    f[i][p[i]] -= minn;
	}

	return minn * d[din];
    }

    return 0; 
}


void flux()
{ 
    int res = 0;
    ok = 1;
    while (ok)
    {
	ok = 0;
	res += bf();
    }
    printf("%d\n", res);
}

int main()
{
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);

    read();
    flux();

    return 0;
}