Cod sursa(job #2698300)

Utilizator miha5092mihai mitrea miha5092 Data 21 ianuarie 2021 17:36:36
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <queue>

using namespace std;

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

int n, m, flow;
int graph[1005][1005][5];
// graph[x][y][0] - exists or not
// graph[x][y][1] - capacity
// graph[x][y][2] - flow

void read()
{
    int x, y, z;
    for(int i=0; i<m; i++)
    {
        in >> x >> y >> z;
        graph[x][y][0] = 1;
        graph[x][y][1] += z;
    }
}

queue <int> q;
int last[1005], mini = 110005;
bool viz[1005];

void bfs(int node)
{
    if(node != n) // if not sink
        for(int sink_n=1; sink_n<=n; sink_n++)
        {
            if(graph[node][sink_n][0] == 1 && graph[node][sink_n][1] > graph[node][sink_n][2] && viz[sink_n] == 0)
            {
                viz[sink_n] ++;
                last[sink_n] = node;
                q.push(sink_n);
            }
        }
}

int main()
{
    in >> n >> m ;
    read();
    do
    {
        q.push(1); // source node
        while(! q.empty())
        {
            bfs(q.front());
            q.pop();
        }
        int i=n;
        while(last[i] != 0)
        {
            mini = min(mini, graph[last[i]][i][1] - graph[last[i]][i][2]);
            i = last[i];
        }
        i=n;
        while(last[i] != 0)
        {
            graph[last[i]][i][2] += mini;
            i = last[i];
            graph[i][last[i]][2] -= mini;
        }
        flow += mini;
        for(int iter=1; iter<=n; iter++)
            viz[iter] = 0;
    }while(mini != 0);
    out << flow;
    return 0;
}