Pagini recente » Cod sursa (job #1346879) | Cod sursa (job #1485428) | Cod sursa (job #306689) | Cod sursa (job #1114140) | Cod sursa (job #2059956)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <ctime>
#include <unordered_map>
#include <iomanip>
#include <complex>
#include <cassert>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define deb(a) cerr<< #a << "= " << (a)<<"\n";
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef long double ld;
typedef complex<double> base;
typedef vector<int> vi;
typedef pair<int,int> pii;
template<class T> ostream& operator<<(ostream& stream, const vector<T> v){ stream << "[ "; for (int i=0; i<(int)v.size(); i++) stream << v[i] << " "; stream << "]"; return stream; }
ll fpow(ll x, ll p, ll m){ll r=1; for (;p;p>>=1){ if (p&1) r=r*x%m; x=x*x%m; } return r;}
int gcd(int a, int b){ if (!b) return a; return gcd(b,a%b);}
ll gcd(ll a, ll b){ if (!b) return a; return gcd(b,a%b);}
struct MaxFlow{
vector<vi> c,f,g;
int s,t,N;
vi ptr,d;
MaxFlow(int N, int s, int t){
this->N = N, this->s = s, this->t = t;
c.resize(N),f.resize(N),g.resize(N);
for (int i=0; i<N; i++)
c[i].resize(N),f[i].resize(N);
}
int getmaxflow(){
int res=0;
for (int i=0; i<N; i++)
fill(all(f[i]),0);
while (bfs()){
ptr.clear();
ptr.resize(N,0);
while (int pushed=dfs(s,(1<<30)))
res+=pushed;
}
return res;
}
int dfs(int nod, int flow){
if (!flow) return 0;
if (nod==t) return flow;
for (int &i=ptr[nod]; i<g[nod].size(); i++){
int nxt=g[nod][i];
if (d[nxt]!=d[nod]+1) continue;
int pushed=dfs(nxt,min(flow,c[nod][nxt]-f[nod][nxt]));
if (pushed){
f[nod][nxt]+=pushed;
f[nxt][nod]-=pushed;
return pushed;
}
}
return 0;
}
void add_uedge(int from, int to, int cap){
g[from].pb(to);
g[to].pb(from);
c[from][to]+=cap;
}
void add_bedge(int from, int to, int cap){
c[from][to]+=cap;
c[to][from]+=cap;
g[from].pb(to);
g[to].pb(from);
}
void print(){
cout << N << "\n";
for (int i=0; i<N; i++, cout << "\n")
for (int j=0; j<N; j++)
cout << c[i][j] << " ";
}
bool bfs(){
d.clear(),d.resize(N,-1);
int *q = new int[N+10],K=0,i;
q[K++]=s; d[s]=0;
for (i=0; i<K; i++){
int nod = q[i];
for (int nxt : g[nod]){
if (c[nod][nxt]-f[nod][nxt]>0 && d[nxt]==-1){
d[nxt]=d[nod]+1;
q[K++]=nxt;
}
}
}
delete[] q;
return d[t]!=-1;
}
};
int N,M;
int main(){
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> N >> M;
MaxFlow mf(N+1,1,N);
int i,x,y,c;
for (i=1; i<=M; i++){
fin >> x >> y >> c;
mf.add_uedge(x,y,c);
}
fout << mf.getmaxflow() << "\n";
return 0;
}