Pagini recente » Cod sursa (job #102155) | Cod sursa (job #2882191) | Cod sursa (job #983870) | Cod sursa (job #2765304) | Cod sursa (job #3039190)
#include <fstream>
#include <queue>
#include <bitset>
using namespace std;
#include <stdio.h>
#include <ctype.h>
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
InParser cin("maxflow.in");
ofstream cout("maxflow.out");
const int NMAX = 1e3;
const int inf = 2e9;
int flux[NMAX + 1][NMAX + 1], t[NMAX + 1];
vector <int> g[NMAX + 1], rg[NMAX + 1];
bitset <NMAX + 1> viz;
queue <int> q;
bool bfs(int x, int n){
viz = 0;
q.push(x);
while(!q.empty()){
int x = q.front();
q.pop();
if(x == n)
return true;
for(auto y : g[x]){
if(viz[y] == 1 || flux[x][y] <= 0)
continue;
t[y] = x;
viz[y] = 1;
q.push(y);
}
}
return false;
}
int main(){
int n = 0, m = 0;
cin >> n >> m;
for(int i = 0; i < m; i++){
int x = 0, y = 0, capacitate = 0;
cin >> x >> y >> capacitate;
flux[x][y] = capacitate;
g[x].push_back(y);
rg[y].push_back(x);
}
int maxi = 0;
while(bfs(1, n)){
for(auto y : rg[n]){
if(viz[y] == 0)
continue;
int mini = inf;
t[n] = y;
int x = y;
while(x != 1){
mini = min(mini, flux[t[x]][x]);
x = t[x];
}
if(mini == 0)
continue;
maxi += mini;
x = n;
while(x != 1){
flux[x][t[x]] += mini;
flux[t[x]][x] -= mini;
x = t[x];
}
}
}
cout << maxi;
return 0;
}