Cod sursa(job #1397018)

Utilizator robertstrecheStreche Robert robertstreche Data 23 martie 2015 10:59:01
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>

#define NMAX 1005
#define INF 0x3f3f3f3f

using namespace std;

queue <int>q;
vector <int>v[NMAX];

bool ap[NMAX];
int n,m,x,y,z,flow;
int boss[NMAX],cap[NMAX][NMAX];

#define DIM 1000
char buff[DIM];
int poz=0;

void citeste(int &numar)
{
     numar = 0;
     while (buff[poz] < '0' || buff[poz] > '9')
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     while ('0'<=buff[poz] && buff[poz]<='9')
     {
          numar = numar*10 + buff[poz] - '0';
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     }
}
inline bool df()
{
    memset(ap,0,sizeof(ap));
    for (;!q.empty();q.pop());

    ap[1]=1;
    q.push(1);
    while (!q.empty())
    {
       int nod=q.front();
       q.pop();
       if (nod==n)continue;
       for (auto it:v[nod])
        if (!ap[it] && cap[nod][it])
        {
          ap[it]=1;
          boss[it]=nod;
          q.push(it);
        }
    }
   return ap[n];
}
int main()
{
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);

   citeste(n);
   citeste(m);

    for (;m;m--)
    {
        citeste(x);
        citeste(y);
        citeste(z);

        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y]+=z;
    }
    ap[1]=1;
    while (df())
    {
        for (auto it:v[n])
          if (ap[it] && cap[it][n])
          {
             int maxflow=cap[it][n];
             for (int i=it;i!=1;i=boss[i])
               maxflow=(maxflow>cap[boss[i]][i]?cap[boss[i]][i]:maxflow);
             for (int i=it;i!=1;i=boss[i])
               cap[boss[i]][i]-=maxflow,
               cap[i][boss[i]]+=maxflow;
             flow+=maxflow;
          }
    }
    printf("%d",flow);

    fclose(stdin);
    fclose(stdout);
}