Pagini recente » Cod sursa (job #2283240) | Cod sursa (job #529129) | Cod sursa (job #1867075) | Cod sursa (job #2406113) | Cod sursa (job #1517782)
#include <fstream>
#include <vector>
#include <bitset>
#include <limits.h>
#include <queue>
#define DIM 639
#define INF INT_MAX
using namespace std;
ifstream fin("cc.in");
ofstream fout("cc.out");
int N, M, beginning, ending, x, y, cap, c, minimum, solution, d, E;
int capacity[DIM][DIM], flow[DIM][DIM], cost[DIM][DIM];
int T[DIM], D[DIM], muchii[DIM][DIM], flux;
vector<int>L[DIM];
bitset<DIM>V;
queue<int>q;
int bellman_ford()
{
for(int i = 1; i <= 2 * N + 1; i ++)
{
D[i] = INF;
V[i] = 0;
}
D[0] = 0;
q.push(0);
while(!q.empty())
{
int node = q.front();
V[ node ] = 0;
q.pop();
for(int i = 0; i < L[ node ].size(); i ++)
{
int neighbour = L[ node ][i];
if( (D[neighbour] > D[ node ] + cost[ node ][neighbour]) && (flow[ node ][neighbour] < capacity[ node ][neighbour] ) )
{
D[neighbour] = D[ node ] + cost[ node ][neighbour];
T[ neighbour ] = node;
if(V[neighbour] == 0)
{
q.push(neighbour);
V[neighbour] = 1;
}
}
}
}
if(D[2 * N + 1] != INF)
{
return 1;
}
return 0;
}
int main()
{
fin >> N;
for(int i = 1; i <= N; i ++)
{
capacity[0][i] = 1;
L[0].push_back(i);
for(int j = N + 1; j <= 2 * N; j ++)
{
L[j].push_back(2 * N + 1);
capacity[j][2 * N + 1] = 1;
fin >> cost[i][j];
cost[j][i] = -cost[i][j];
L[i].push_back(j);
L[j].push_back(i);
capacity[i][j] = 1;
}
}
while(bellman_ford())
{
minimum = INF;
int x = 2 * N + 1;
while(x != 0)
{
if(minimum > capacity[ T[x] ][x] - flow[ T[x] ][x] )
{
minimum = capacity[ T[x] ][x] - flow[ T[x] ][x];
}
x = T[x];
}
x = 2 * N + 1;
while(x != 0)
{
solution += minimum * cost[ T[x] ][x];
flow[ T[x] ][x] += minimum;
flow[x][ T[x] ] -= minimum;
x = T[x];
}
flux += minimum;
}
fout << solution;
return 0;
}