Pagini recente » Cod sursa (job #1270723) | Cod sursa (job #2724354) | Cod sursa (job #828524) | Cod sursa (job #2709177) | Cod sursa (job #951155)
Cod sursa(job #951155)
#include<fstream>
#include<vector>
#include<bitset>
#define NMAX 20002
using namespace std;
int no_left_nodes,no_right_nodes,no_edges;
int match1[NMAX/2],match2[NMAX/2];
vector <int> adjacent_nodes[NMAX];
bitset <NMAX/2> visited;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
void scan() {
in>>no_left_nodes>>no_right_nodes>>no_edges;
int left_node,right_node;
for (int i = 0; i < no_edges; ++i) {
in>>left_node>>right_node;
adjacent_nodes[left_node].push_back(right_node);
}
}
bool DFS(int node) {
if (visited[node] == true) return false;
visited[node] = true;
for (int i = 0; i < adjacent_nodes[node].size(); ++i)
if (match2[adjacent_nodes[node][i]] == -1) {
match1[node] = adjacent_nodes[node][i];
match2[adjacent_nodes[node][i]] = node;
return true;
}
for (int i = 0; i < adjacent_nodes[node].size(); ++i)
if (DFS(match2[adjacent_nodes[node][i]])) {
match1[node] = adjacent_nodes[node][i];
match2[adjacent_nodes[node][i]] = node;
return true;
}
return false;
}
int Hopcroft_Karp() {
bool changes;
int edges = 0;
for (int i = 1; i <= no_left_nodes; ++i)
match1[i] = -1;
for (int i = 1; i <= no_right_nodes;++i)
match2[i] = -1;
do {
changes = false;
for (int i = 1; i <= no_left_nodes; ++i)
visited[i] = false;
for (int i = 1; i <= no_left_nodes; ++i)
if (match1[i] == -1)
if (DFS(i)) {
changes = true;
edges++;
}
} while (changes == true);
return edges;
}
int main() {
scan();
out<<Hopcroft_Karp()<<"\n";
for (int i = 1; i <= no_left_nodes; ++i)
if (match1[i] != -1)
out<<i<<" "<<match1[i]<<endl;
return 0;
}