Pagini recente » Cod sursa (job #1602075) | Cod sursa (job #2653255) | Cod sursa (job #1663012) | Cod sursa (job #2506399) | Cod sursa (job #826683)
Cod sursa(job #826683)
//clasa flowSolver poate fi folosita cu incredere pentru concursuri gen TopCoder.
//Nu ma supar daca o ciorditi :P
#include <stdio.h>
#include <vector>
using namespace std;
//MODIFICA NMAX IN FUNCTIE DE PROBLEMA!!!
const int NMAX = 1050;
int F[1000][1000], C[1000][1000];
struct flowSolver
{
//public:
int source, sink, maxflow, N;
int father[NMAX], vis[NMAX], Q[NMAX], p, u;
vector <int> G[NMAX];
void initFlow (int sursa, int dest, int _N)
{
source = sursa; sink = dest; N = _N;
}
void addEdge(int x0, int y0, int cost, bool isDirected)
{
G[x0].push_back(y0);
G[y0].push_back(x0);
C[x0][y0] = cost;
if (isDirected == false)
G[y0][x0] = cost;
}
void initBFS()
{
int i;
for (i = 0; i <= N; i ++)
father[i] = 0, vis[i] = 0;
p = 1; u = 0;
}
bool BFS()
{
initBFS();
Q[++ u] = source; vis[source] = 1; father[source] = -1;
vector <int> :: iterator it;
while (p <= u)
{
int nod = Q[p];
for (it = G[nod].begin(); it != G[nod].end(); it ++)
if (vis[*it] == 0 && F[nod][*it] < C[nod][*it])
{
father[*it] = nod;
vis[*it] = 1;
Q[++ u] = *it;
}
p ++;
}
return vis[sink];
}
void augment()
{
vector <int> :: iterator it;
int nod, fmin;
for (it = G[sink].begin(); it != G[sink].end(); it ++)
{
fmin = C[*it][sink] - F[*it][sink]; nod = *it;
while (nod != source && fmin > 0)
{
if (C[father[nod]][nod] - F[father[nod]][nod] < fmin)
fmin = C[father[nod]][nod] - F[father[nod]][nod];
nod = father[nod];
}
if (fmin)
{
nod = *it;
F[*it][sink] += fmin; F[sink][*it] -= fmin;
while (nod != source)
{
F[father[nod]][nod] += fmin; F[nod][father[nod]] -= fmin;
nod = father[nod];
}
maxflow += fmin;
}
}
}
int solve()
{
maxflow = 0;
while (BFS())
augment();
return maxflow;
}
};
int main()
{
int i, N, M;
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
scanf("%d%d", &N, &M);
flowSolver sol;
sol.initFlow(1, N, N);
for (i = 1; i <= M; i ++)
{
int x0, y0, c;
scanf("%d%d%d", &x0, &y0, &c);
sol.addEdge(x0, y0, c, 1);
}
printf("%d", sol.solve());
return 0;
}