Cod sursa(job #679713)

Utilizator balakraz94abcd efgh balakraz94 Data 13 februarie 2012 17:38:33
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include<cstdio>
#include<vector>
#include<queue>
#define infile "maxflow.in"
#define outfile "maxflow.out"
#define n_max 1005
#define INF 1<<30
#define pb push_back
#define nxt *it
#define FOR(g) \
    for(vector<int> :: iterator it = g.begin(); it!=g.end(); ++it)
using namespace std;

int N, M;

vector < int > v[n_max], edge[n_max];

int flow[n_max][n_max]; 

int Src, Sink;

int MaxFlow;


void citeste()
{
    freopen(infile,"r",stdin);
    
    int x, y, cost;
    
    scanf("%d %d",&N, &M);
    
    while(M--)
    {
        scanf("%d %d %d",&x,&y,&cost);
        
        v[x].pb(y);
        v[y].pb(x);
        flow[x][y] = cost;
    }
    
    Src = 1;
    Sink = N;
    
    fclose(stdin);
}


inline int bfs()
{
    vector < int > dist(n_max, -1);
    queue < int > q;
    
	for(int i=0;i<n_max; ++i)
		edge[i].clear();
	
    q.push(Src);
    dist[Src] = 0;;
    
    int nod;
    
    while(!q.empty())
    {
        nod = q.front();
        q.pop();
        
        if(nod == Sink)
            return 1;
        
        FOR(v[nod])
        {
            if(flow[nod][nxt] == 0)
                continue;
            
            if(dist[nxt] == -1)
            {
                q.push(nxt);
                dist[nxt] = dist[nod] + 1;
                edge[nod].pb(nxt);
            }
            else if(dist[nxt] == dist[nod] + 1)
                edge[nod].pb(nxt);
        }
    }
	
	return (dist[Sink] != -1);
}



inline int dfs(int nod, int cap)
{
    if(cap == 0)
        return 0;
    
    if(nod == Sink)
        return cap;
    
    int flux = 0;
    
    FOR(edge[nod])
    {
        if(flow[nod][nxt] == 0)
            continue;
        
        int r = dfs(nxt, min(cap - flux, flow[nod][nxt]));
        
        if(r)
        {
            flow[nod][nxt] -= r;
            flow[nxt][nod] += r;
            flux += r;
        }
    }
    return flux;
}



void afiseaza()
{
    freopen(outfile,"w",stdout);
    
    printf("%d\n",MaxFlow);
    
    fclose(stdout);
}


int main()
{
    citeste();
	
    while( bfs())
		MaxFlow += dfs(Src, INF);
	
    afiseaza();
    
    return 0;
}