Pagini recente » Cod sursa (job #2659930) | Cod sursa (job #1342602) | Cod sursa (job #2408283) | Cod sursa (job #1576344) | Cod sursa (job #2208888)
#include <fstream>
#include <list>
using namespace std;
struct graph {
int vertexCount;
int edgeCount;
int leftPart;
list<int>* adjList;
int* matchL;
int* matchR;
bool* viz;
int matched = 0;
};
void readGraph(graph& g, ifstream& in) {
int a, b;
in >> a >> b >> g.edgeCount;
g.vertexCount = a + b;
g.leftPart = a;
g.adjList = new list<int>[g.vertexCount + 1];
for (int i = 1; i <= g.edgeCount; i++) {
int v1, v2;
in >> v1 >> v2;
v2 += a;
g.adjList[v1].push_back(v2);
}
g.matchL = (int*)calloc(g.vertexCount + 1, sizeof(int));
g.matchR = (int*)calloc(g.vertexCount + 1, sizeof(int));
g.viz = (bool*)calloc(g.vertexCount + 1, sizeof(bool));
}
bool findMatch(graph& g, int vertex) {
if (g.viz[vertex])
return false;
g.viz[vertex] = true;
for (auto adj : g.adjList[vertex]) {
if (g.matchR[adj] == 0) {
g.matchL[vertex] = adj;
g.matchR[adj] = vertex;
return true;
}
}
for (auto adj : g.adjList[vertex]) {
if (findMatch(g, g.matchR[adj])) {
g.matchL[vertex] = adj;
g.matchR[adj] = vertex;
return true;
}
}
return false;
}
int hopcroftKarp(graph& g) {
bool changed = true;
int maxMatching = 0;
while (changed) {
changed = false;
for (int i = 1; i <= g.vertexCount; i++) g.viz[i] = false;
for (int i = 1; i <= g.leftPart; i++)
if (!g.matchL[i]) {
bool matched = findMatch(g, i);
changed |= matched;
}
}
return g.matched;
}
int main() {
graph g;
ifstream in("cuplaj.in");
readGraph(g, in);
in.close();
int maxMatching = hopcroftKarp(g);
g.matched = 0;
for (int i = 1; i <= g.leftPart; i++)
if (g.matchL[i])
g.matched++;
ofstream out("cuplaj.out");
out << g.matched << "\n";
for (int i = 1; i <= g.leftPart; i++) {
if (g.matchL[i])
out << i << " " << g.matchL[i] - g.leftPart << "\n";
}
out.close();
return 0;
}