Pagini recente » Cod sursa (job #183335) | Cod sursa (job #2678660) | Cod sursa (job #2651198) | Cod sursa (job #2381477) | Cod sursa (job #1061167)
#include <fstream>
#include <iostream>
#include <queue>
#include <bitset>
using namespace std ;
const int Nmax = 5000;
short C[Nmax][Nmax], F[Nmax][Nmax] , capacity[Nmax][Nmax], Father[Nmax] ;
short n ,source,destination ,sum, maxflow , sol ;
bool ok;
bitset < Nmax > viz;
vector < int > Graph[Nmax];
ofstream g("algola.out");
inline void Read()
{
int i , x, y ,c,m;
ifstream f("algola.in");
f >> n >> m;
for(i = 1;i <= n; ++i)
{
f >> x;
sum += x;
if(x)
ok = 1;
///adaugam nodurile cu starea 0
Graph[source].push_back(i);
Graph[i].push_back(source);
C[source][i] = x;
}
for(i = 1;i <= m; ++i)
{
f >> x >> y >> c;
capacity[x][y] = capacity[y][x] = c;
}
f.close();
}
inline void UpdateGraph(const int time)
{
int i,j,x,y;
for(i = 1;i <= n; ++i)
{
x = (time-1)*n+i;
y = time*n+i;
Graph[x].push_back(y);
Graph[y].push_back(x);
C[x][y] = Nmax;
/**adaugam muchie de la starea (nod,time-1) la starea (nod,time) de capacitate infinit
care semnifica ca la momentul de timp time se poate stationa in nodul nod
*/
for(j = 1;j <= n; ++j)
{
if(capacity[i][j] == 0)
continue;
y = time*n + j;
Graph[x].push_back(y);
Graph[y].push_back(x);
C[x][y] = capacity[i][j];
/**
adugam muchie de la starea (nod,time-1) la starea (j,time) cu capacitatea muchiei (nod,j)
cu semnificatia ca la momentul de timp time se poate trece de la nodul node la nodul j
*/
}
}
destination = time*n+1;
}
inline bool BFS()
{
queue < int > Q;
viz = 0;
viz[source] = 1;
int node,i;
vector < int > ::iterator it;
for(Q.push(source); !Q.empty() ; Q.pop())
{
node = Q.front();
if(node==destination)
continue ;
for(it = Graph[node].begin();it != Graph[node].end(); ++it)
{
i = *it;
if(F[node][i] < C[node][i] && !viz[i])
{
viz[i] = 1;
Q.push(i);
Father[i] = node;
}
}
}
return viz[destination];
}
inline bool MaxFlow()
{
int i, _min , node;
vector < int > :: iterator it;
while(BFS())
{
for(it = Graph[destination].begin(); it != Graph[destination].end(); ++it)
{
i = *it;
if(!viz[i] || F[i][destination] == C[i][destination] || C[i][destination] ==0)
continue;
Father[destination] = i;
_min = Nmax;
for(node = destination ; node != source ; node = Father[node])
_min = min(_min,C[Father[node]][node] - F[Father[node]][node]);
if(!_min)
continue;
for(node = destination ; node != source ; node = Father[node])
{
F[Father[node]][node] += _min;
F[node][Father[node]] -= _min;
}
maxflow += _min;
}
}
return (maxflow == sum);
}
inline void Solve()
{
if(!ok)
return ;
for(int i = 1;i < 100; ++i)///incercam fiecare timp sa vedem daca este solutie
{
UpdateGraph(i);
sol = i;
if(MaxFlow())
return ;
}
}
inline void Write()
{
g<<sol<<"\n";
}
int main()
{
Read();
Solve();
Write();
return 0;
}