Cod sursa(job #1769368)

Utilizator jason2013Andronache Riccardo jason2013 Data 2 octombrie 2016 14:05:04
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include<bits/stdc++.h>
#define INFINIT 200000000
using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

const int NMax = 1005;
const int MMax = 5005;

int c[1005][1005], f[1005][1005];
int t[1005];
int n, m;
vector<int> vecini[1005];
queue<int> Queue;

bool bfs()
{
    queue<int> q;
    int current, next;
    int i, j, ok = 0;
    memset(t, 0, sizeof(t));
    t[1] = -1;
    q.push(1);
    while(!q.empty())
    {
        current = q.front();
        q.pop();
        for(i = 0, j = vecini[current].size(); i < j; i++)
        {
            next = vecini[current][i]; // vecini[1][0]
            if(next == n) // daca urmatorul  = nodul destinatie
            {
               if(c[current][next] > f[current][next])
               {
                   ok = 1;
                   Queue.push(current);
               }
            }
            else if(!t[next] && c[current][next] > f[current][next])
            {
                q.push(next);
                t[next] = current;
            }
        }
    }
    if(ok) return 1;
    else return 0;
}

int main()
{
    ifstream in;
    in.open("maxflow.in");
    ofstream out("maxflow.out");
    int i, j, v1, v2, v3, maxflow = 0;
    in >> n >>m;
    for(i = 0; i < m; i++)
    {
        in >> v1 >> v2 >> v3;
        c[v1][v2] = v3;
        vecini[v1].push_back(v2);
        vecini[v2].push_back(v1);
    }

    while(bfs())
    {
        while(!Queue.empty())
        {
            v2 = Queue.front();
            Queue.pop();
            v1 = c[v2][n] - f[v2][n];
            i = v2;
            while(i!=1)
            {
                if(v1<(c[t[i]][i]-f[t[i]][i]))
                    v1 = v1;
                else
                    v1 =(c[t[i]][i]-f[t[i]][i]);
                i=t[i];
            }
            if(v1 == 0) continue;
            i = v2;
            f[v2][n] += v1;
            f[n][v2] -= v1;
            while(i!=1)
            {
                f[t[i]][i]+=v1;
                f[i][t[i]]-=v1;
                i=t[i];
            }
            maxflow += v1;
        }
    }
    out<<maxflow;
    return 0;
}