Cod sursa(job #2129409)

Utilizator DeleDelegeanu Alexandru Dele Data 12 februarie 2018 20:10:18
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#include <string.h>
#include <vector>
#include <queue>
#define nmax 1005
#define inf 999999999
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n,m,i,flow,fmin,nod,x,y,z;
int capacitate[nmax][nmax],flux[nmax][nmax];
int viz[nmax],t[nmax];
vector<int> a[nmax];
vector<int>::iterator it;
int bfs(){
    memset(viz, 0, sizeof(viz));
    queue <int> q;
    q.push(1);
    viz[1]=1;
    while(!q.empty())
    {
        int nod=q.front();
        q.pop();
        if(nod==n)continue;
        for (it=a[nod].begin(); it!=a[nod].end(); ++it)
        {
            int nxt=*it;
            if (!viz[nxt])
            {
                if (flux[nod][nxt]==capacitate[nod][nxt])continue;
                q.push(nxt);
                t[nxt]=nod;
                viz[nxt]=1;
            }
        }
    }
    return viz[n];
}
int main()
{
    f>>n>>m;
    for(i=1 ; i<=m ; ++i)
    {
        f>>x>>y>>z;
        capacitate[x][y]=z;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    while (bfs())
    {
        for (it=a[n].begin(); it != a[n].end(); ++it)
        {
            int nxt=*it;
            int nod=n;
            int min_flow=inf;
            t[n]=nxt;
            while(nod!=1)
            {
                min_flow=min(min_flow, capacitate[ t[nod] ][nod]-flux[ t[nod] ][nod]);
                nod=t[nod];
            }
            nod=n;
            while(nod!=1)
            {
                flux[ t[nod] ][nod]+=min_flow;
                flux[nod][ t[nod] ]-=min_flow;
                nod=t[nod];
            }
            flow+=min_flow;
        }
    }
    g<<flow<<'\n';
    return 0;
}