Pagini recente » Cod sursa (job #831405) | Cod sursa (job #2475753) | Cod sursa (job #2565582) | Cod sursa (job #2654968) | Cod sursa (job #2958706)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
int graf[20001][20001];
int tati[20001];
bool vizitat[20001];
bool bfs(int n)
{
queue<int> coada;
for(int i = 0; i <= n; i++)
{
vizitat[i] = false;
tati[i] = -1;
}
coada.push(0);
vizitat[0] = true;
while(coada.empty() == false)
{
int nod = coada.front();
coada.pop();
for(int i = 0; i <= n; i++)
{
if(graf[nod][i] > 0 && vizitat[i] == false)
{
coada.push(i);
vizitat[i] = true;
tati[i] = nod;
if(i == n)
{
return true;
}
}
}
}
return false;
}
int flux(int n)
{
int flux_maxim = 0;
while(bfs(n))
{
for(int i = 1; i < n; i++)
{
if(graf[i][n] > 0 && vizitat[i] == true)
{
int penultim = i;
vector<int> drum_c;
drum_c.push_back(n);
drum_c.push_back(penultim);
int tata = tati[penultim];
while(tata != -1)
{
drum_c.push_back(tata);
tata = tati[tata];
}
int bottleneck = 2;
for(int i = 1; i < drum_c.size(); i++)
{
bottleneck = min(bottleneck, graf[drum_c[i]][drum_c[i-1]]);
}
flux_maxim = flux_maxim + bottleneck;
for(int i = 1; i < drum_c.size(); i++)
{
graf[drum_c[i]][drum_c[i-1]] = graf[drum_c[i]][drum_c[i-1]] - bottleneck;
graf[drum_c[i-1]][drum_c[i]] = graf[drum_c[i-1]][drum_c[i]] + bottleneck;
}
}
}
}
return flux_maxim;
}
int main()
{
int n1, n2, m;
f >> n1 >> n2 >> m;
int a, b;
for(int i = 1; i <= n1; i++)
{
graf[0][i] = 1;
}
for(int i = 1; i <= n2; i++)
{
graf[i + n1][n1 + n2 + 1] = 1;
}
for(int i = 0; i < m; i++)
{
f >> a >> b;
graf[a][b + n1] = 1;
}
g << flux(n1 + n2 + 1) << "\n";
for(int i = 1; i <= n1; i++)
{
for(int j = n1 + 1; j <= n1 + n2; j++)
{
if(graf[j][i] != 0)
{
g << i << " " << j - n1 << "\n";
}
}
}
return 0;
}