Cod sursa(job #1402696)

Utilizator radarobertRada Robert Gabriel radarobert Data 26 martie 2015 18:50:17
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 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 q[1002];
int n;

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

    int node;
    for (int j = 1; j <= q[0]; j++)
    {
        node = q[j];
        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[++q[0]] = g[node][i];
                father[g[node][i]] = node;
            }
    }
    return vis[n];
}

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;
    int k;
    int fmax;
    while (bfs())
    {
        for (int i = 0; i < g[n].size(); i++)
        {
            if (f[g[n][i]][n] == c[g[n][i]][n])
                continue;
            fmax = c[g[n][i]][n] - f[g[n][i]][n];
            for (k = g[n][i]; k != 1; k = father[k])
            {
                int ta = c[father[k]][k] - f[father[k]][k];
                if (ta < fmax)
                    fmax = ta;
            }
            f[g[n][i]][n] += fmax;
            for (k = g[n][i]; k != 1; k = father[k])
            {
                f[father[k]][k] += fmax;
                f[k][father[k]] -= fmax;
            }

            flow += fmax;
        }
    }

    out << flow << '\n';

    return 0;
}