Cod sursa(job #1561166)

Utilizator DrumeaVDrumea Vasile DrumeaV Data 3 ianuarie 2016 18:52:47
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <stdio.h>
#include <string.h>
#include <vector>
#include <deque>
#include <algorithm>

using namespace std;

const int Mn = 1004;
const int oo = 1 << 30;

int n,m;
int parent[Mn];
int flow[Mn][Mn],capacity[Mn][Mn];
bool visited[Mn];
vector< int > graph[Mn];
deque< int > dq;

bool bfs()
{
    dq.clear();
    dq.push_back(1);
    memset(visited,0,sizeof(visited));
    visited[1] = 1;

    while (!dq.empty())
    {
        int x = dq.front();

        dq.pop_front();

        if (x == n)
           continue;

        for (int i = 0;i < graph[x].size();i++)
        {
            int y = graph[x][i];

            if (visited[y] || capacity[x][y] == flow[x][y])
               continue;

            visited[y] = 1;
            dq.push_back(y);
            parent[y] = x;
        }
    }

    return visited[n];
}

int max_flow()
{
    int sol = 0;

    while (bfs())
    {
        for (int i = 0;i < graph[n].size();i++)
        {
            int x = graph[n][i],y = oo;

            if (!visited[n] || capacity[x][n] == flow[x][n])
               continue;

            parent[n] = x;

            for (x = n;x != 1;x = parent[x])
                y = min(y,capacity[parent[x]][x] - flow[parent[x]][x]);

            if (!y)
               continue;

            for (x = n;x != 1;x = parent[x])
            {
                flow[parent[x]][x] += y;
                flow[x][parent[x]] -= y;
            }

            sol += y;
        }
    }

    return sol;
}

int main()
{
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);

     scanf("%d %d",&n,&m);

     while (m--)
     {
         int x,y,z;
         scanf("%d %d %d",&x,&y,&z);
         capacity[x][y] += z;
         graph[x].push_back(y);
         graph[y].push_back(x);
     }

     printf("%d\n",max_flow());

  return 0;
}