Cod sursa(job #2193903)

Utilizator mrhammerCiocan Cosmin mrhammer Data 11 aprilie 2018 19:54:36
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>
#include<stdio.h>
#define N_MAX 1001
#define MAX_VAL 999999
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n,m;
struct vertex
{
    int target;
    int capacity;
    int rev;
};
int graph[N_MAX][N_MAX];
vector< int > target_map[N_MAX];
vector<int> stk;
queue<int> q;
bool visited[N_MAX];
int order[N_MAX];
int max_flow;
bool bfs()
{
    bool ok_s = false;
    memset(order,-1,sizeof(order));
    memset(visited,0,sizeof(visited));
    order[0] = 0;
    q.push(0);
    while(!q.empty())
    {
        int x = q.front();
        visited[x] = true;
        q.pop();
        for(int i=0;i<n;i++)
        {
            if(graph[x][i] > 0)
            {

                if(order[i] == -1) order[i] = order[x]+1;
                if(order[i] > order[x]) target_map[x].push_back(i);
                if(visited[i] == false) visited[i] = true,q.push(i);
            }
        }
    }
    if(order[n-1] != -1) ok_s = true;
    return ok_s;
}
void update_stack(int min_val)
{
    for(int i=stk.size()-2;i>=0;i--)
    {
        graph[ stk[i] ][ stk[i+1] ] -= min_val;
        graph[ stk[i+1] ][ stk[i] ] += min_val;
        stk.pop_back();
    }
}
void dfs(int node,int val_min)
{
    if(node == n-1)
    {
        stk.push_back(node);
        //cout<<node<<" --> "<<val_min<<"\n";
        max_flow += val_min;
        update_stack(val_min);
        return;
    }
    for(int i=target_map[node].size()-1;i>=0;i--)
    {
        //cout<<node<<" ";
        stk.push_back(node);
        if(graph[node][ target_map[node][i] ] < val_min) val_min = graph[node][ target_map[node][i] ];
        dfs(target_map[node][i],val_min);
        target_map[node].pop_back();
    }
}
/*void test()
{
    cout<<bfs();
    dfs(0,MAX_VAL);
    //cout<<"\n";
    //cout<<order[n-1];
    //cout<<"\n";
}*/
int main()
{
    fin>>n>>m;
    int k1,k2,k3;
    max_flow = 0;
    for(int i=0;i<m;i++)
    {
        fin>>k1>>k2>>k3;
        graph[k1-1][k2-1] = k3;
        graph[k2-1][k1-1] = 0;
    }
    while(bfs() == true)
    {
        dfs(0,MAX_VAL);
    }
    fout<<max_flow<<"\n";
}