Cod sursa(job #1944241)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 29 martie 2017 00:51:05
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#define MaxN 1005
#define I Graph[Destination][i]
#define INF 2140000000
  
using namespace std;
  
FILE *IN,*OUT;
int N,M,X,Y,C;
int capacity[MaxN][MaxN],flow[MaxN][MaxN],father[MaxN];
bool visited[MaxN];
vector <int> Graph[MaxN];
queue <int> Q;
bool BFS(int Start,int End)
{
    memset(visited,0,sizeof visited);
    memset(father,0,sizeof father);
    visited[Start]=true;
    Q.push(Start);
  
    while(!Q.empty())
    {
        for(int i=0;i<Graph[Q.front()].size();i++)
          
            if(!visited[Graph[Q.front()][i]]&&capacity[Q.front()][Graph[Q.front()][i]]-flow[Q.front()][Graph[Q.front()][i]]>0)
            {
                Q.push(Graph[Q.front()][i]);
                father[Graph[Q.front()][i]]=Q.front();
                visited[Graph[Q.front()][i]]=true;
            }
      
        Q.pop();
    }
      
    if(father[End])
        return true;
      
    return false;
}
int Flow(int Source,int Destination)
{
    int F=0,Min;
      
    while(BFS(Source,Destination))
    {
        for(int i=0;i<Graph[Destination].size();i++)
            if(capacity[I][Destination]-flow[I][Destination]>0)
            {
                Min=capacity[I][Destination]-flow[I][Destination];
      
                for(int j=I;j!=Source;j=father[j])
                    if(capacity[father[j]][j]-flow[father[j]][j]<Min)
                        Min=capacity[father[j]][j]-flow[father[j]][j];
                flow[I][Destination]+=Min;
                flow[Destination][I]-=Min;
                for(int j=I;j!=Source;j=father[j])
                    flow[father[j]][j]+=Min,flow[j][father[j]]-=Min;
                F+=Min;
            }   
    }
    return F;
}
int main()
{
    IN=fopen("maxflow.in","r");
    OUT=fopen("maxflow.out","w");
  
    fscanf(IN,"%d%d",&N,&M);
    for(int i=1;i<=M;i++)
    {
        fscanf(IN,"%d%d%d",&X,&Y,&C);
        Graph[X].push_back(Y);
        Graph[Y].push_back(X);
        capacity[X][Y]=C;
    }
    fprintf(OUT,"%d",Flow(1,N));
    return 0;
}