Cod sursa(job #3039141)

Utilizator AndreiBOTOBotocan Andrei AndreiBOTO Data 28 martie 2023 11:03:24
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.77 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>

#pragma GCC optimize("unroll-loops")
#pragma gcc optimize("Ofast")

///#include <tryhardmode>
///#include <GODMODE::ON>

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

InParser fin ("fmcm.in");
ofstream fout ("fmcm.out");

const int INF=2e9;
const int NMAX=355;

vector<pair<int,int>>v[NMAX];

int t[NMAX];
int flux[NMAX][NMAX];
int dist[NMAX];
bool viz[NMAX];

int n,m,s,d;

int bellman()
{
    int i;
    for(i=1;i<=n;i++)
    {
        viz[i]=false;
        dist[i]=INF;
    }
    queue<int>q;
    q.push(s);
    dist[s]=0;
    viz[s]=true;
    while(!q.empty())
    {
        int p=q.front();
        q.pop();
        viz[p]=false;
        for(auto i:v[p])
        {
            if(flux[p][i.first]>0 && dist[i.first]>dist[p]+i.second)
            {
                dist[i.first]=dist[p]+i.second;
                if(!viz[i.first])
                {
                    q.push(i.first);
                    viz[i.first]=true;
                }
                t[i.first]=p;
            }
        }
    }
    return dist[d];
}

int main()
{
    int i,x,y,maxi=0,mini;
    bool ok=true;
    fin>>n>>m>>s>>d;
    for(i=1;i<=m;i++)
    {
        int cost,cap;
        fin>>x>>y>>cap>>cost;
        v[x].push_back(make_pair(y,cost));
        v[y].push_back(make_pair(x,-cost));
        flux[x][y]=cap;
    }
    while(ok)
    {
        mini=INF;
        int suma=bellman();
        if(suma==INF)
            break;
        x=d;
        while(x!=s)
        {
            mini=min(mini,flux[t[x]][x]);
            x=t[x];
        }
        x=d;
        while(x!=s)
        {
            flux[x][t[x]]+=mini;
            flux[t[x]][x]-=mini;
            x=t[x];
        }
        maxi=maxi+mini*suma;
    }
    fout<<maxi;
    return 0;
}