Pagini recente » Cod sursa (job #775537) | Cod sursa (job #875719) | Cod sursa (job #484195) | Cod sursa (job #718159) | Cod sursa (job #798594)
Cod sursa(job #798594)
//Vasilut
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>
#define NN 1001
#define pb push_back
using namespace std;
ofstream out("maxflow.out");
int cap[NN][NN],flow[NN][NN],uz[NN],n,m,father[NN],flux;
vector<int>G[NN];
typedef vector<int>::iterator IT;
void read();
bool BFS();
void solve();
int main()
{
read();
solve();
out<<flux;
return 0;
}
void read()
{
ifstream in("maxflow.in");
in>>n>>m;
for(int x,y,c ; m ;--m)
{
in>>x>>y>>c;
G[x].pb(y);
G[y].pb(x);
cap[x][y]=c;
}
}
bool BFS()
{
memset(uz,0,sizeof(uz));
uz[1]=1;
queue<int>Q;
Q.push(1);
int k;
while(!Q.empty())
{
k=Q.front();
Q.pop();
if(k!=n)
for(IT I=G[k].begin();I!=G[k].end();++I)
if(!uz[*I] && cap[k][*I] > flow[k][*I])
{
uz[*I]=1;
father[*I]=k;
Q.push(*I);
}
}
return uz[n];
}
void solve()
{
int solution=0;
for(;BFS();)
{
for(int i=1;i<n;i++)
if(flow[i][n] < cap[i][n] )///mai pot adauga
{
solution=cap[i][n]-flow[i][n];
for(int j=i;j!=1;j=father[j] )//merg pe drum ,poate gasesc o solutie mai buna
if(cap[father[j]][j] - flow[father[j]][j] < solution)//am gasit
solution=cap[father[j]][j] - flow[father[j]][j];//inbunatatim solutia
flow[i][n]+=solution;//maresc fluxul
flow[n][i]-=solution;
for(int j=i;j!=1;j=father[j])//merg pe drum,pt a adauga la fluxul existent o noua valoare(solution)
{
flow[father[j]][j]+=solution;//am adaugat
flow[j][father[j]]-=solution;
}
flux+=solution;
}
}
}