Pagini recente » Cod sursa (job #153539) | Cod sursa (job #410957) | Cod sursa (job #3281384) | Cod sursa (job #3187568) | Cod sursa (job #2149702)
#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<ll> 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;
vi tt;
ll s,t,N;
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);
}
ll getmaxflow(){
ll res=0;
for (int i=0; i<N; i++)
fill(all(f[i]),0);
while (bfs()){
int nod;
for (nod=0; nod<N; nod++){
if (c[nod][t]-f[nod][t]==0 || tt[nod]==-1) continue;
tt[t]=nod;
ll cr,fmin=(1LL<<60);
for (cr=t; cr!=s; cr=tt[cr])
fmin=min(fmin,c[tt[cr]][cr]-f[tt[cr]][cr]);
res+=fmin;
for (cr=t; cr!=s; cr=tt[cr]){
f[tt[cr]][cr]+=fmin;
f[cr][tt[cr]]-=fmin;
}
}
}
return res;
}
void add_uedge(int from, int to, ll cap){
g[from].pb(to);
g[to].pb(from);
c[from][to]+=cap;
}
void add_bedge(int from, int to, ll cap){
g[from].pb(to);
g[to].pb(from);
c[from][to]+=cap;
c[to][from]+=cap;
}
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(){
tt.clear(),tt.resize(N,-1);
int *q = new int[N+10],K=0,i;
bool *v = new bool[N+10];
for (i=0; i<N; i++) v[i]=0;
q[K++]=s; v[s]=1;
bool ok=0;
for (i=0; i<K; i++){
int nod = q[i];
for (int nxt : g[nod]){
if (c[nod][nxt]-f[nod][nxt]>0 && !v[nxt]){
if (nxt==t){
ok=1;
continue;
}
tt[nxt]=nod;
q[K++]=nxt;
v[nxt]=1;
}
}
}
delete[] q;
delete[] v;
return ok;
}
};
int N,M;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
MaxFlow mf(N+3,1,N);
ll i,x,y,c;
for (i=1; i<=M; i++){
cin >> x >> y >> c;
if (x==y) continue;
mf.add_bedge(x,y,c);
}
cout << mf.getmaxflow() << "\n";
return 0;
}