Cod sursa(job #1402664)

Utilizator radarobertRada Robert Gabriel radarobert Data 26 martie 2015 18:33:08
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int INF = 0x3f3f3f3f;

queue<int> q;
vector<int> g[1002];
int c[1002][1002], f[1002][1002];
bool vis[1002];
int father[1002];
int n;

bool bfs()
{
    memset(vis, 0, sizeof(bool) * (n+1));
    q.push(1);
    vis[1] = true;

    int node;
    while (!q.empty())
    {
        node = q.front();
        q.pop();
        for (int i = 0; i < g[node].size(); i++)
            if (!vis[g[node][i]] && f[node][g[node][i]] != c[node][g[node][i]])
            {
                vis[g[node][i]] = 1;
                q.push(g[node][i]);
                father[g[node][i]] = node;
            }
    }
    return vis[n];
}

inline int Min(int a, int b)
{
    if (a < b)
        return a;
    return b;
}

int main()
{
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");

    int m;
    in >> n >> m;
    for (int x, y, z, i = 1; i <= m; i++)
    {
        in >> x >> y >> z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }

    int flow = 0;
    while (bfs())
    {
        for (vector<int>::iterator i = g[n].begin(); i != g[n].end(); i++)
        {
            if (f[*i][n] == c[*i][n])
                continue;
            int fmax = INF;
            for (int k = n; k != 1; k = father[k])
                fmax = Min(fmax, c[father[k]][k] - f[father[k]][k]);
            for (int k = n; k != 1; k = father[k])
            {
                f[father[k]][k] += fmax;
                f[k][father[k]] -= fmax;
            }

            flow += fmax;
        }
    }

    out << flow << '\n';

    return 0;
}