Pagini recente » Istoria paginii runda/stele/clasament | Cod sursa (job #1539142) | Cod sursa (job #1824540)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#define MaxN 1005
#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=1;i<=N;i++)
if(capacity[i][Destination]-flow[i][Destination]>0)
{
Min=INF;
if(capacity[i][Destination]-flow[i][Destination]<Min)
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];
if(Min==INF)continue;
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;
}