C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 510
int n1, n2, m, visited[MAXSIZE], match[MAXSIZE];
struct Edge {
int to;
struct Edge *nxt;
} *edges[MAXSIZE];
void addEdge(int from, int to) {
struct Edge *s = (struct Edge*) calloc(1, sizeof(struct Edge));
s->to = to;
s->nxt = edges[from];
edges[from] = s;
}
void init() {
scanf("%d%d%d", &n1, &n2, &m);
int u, v;
while (m--) {
scanf("%d%d", &u, &v);
addEdge(u, v);
}
}
int find(int u) {
for (struct Edge *p = edges[u]; p != NULL; p = p->nxt) {
int v = p->to;
if (!visited[v]) {
visited[v] = 1;
if (!match[v] || find(match[v])) {
match[v] = u;
return 1;
}
}
}
return 0;
}
int Hungarian() {
int res = 0;
for (int u = 1; u <= n1; ++u) {
memset(visited, 0, sizeof(visited));
if (find(u)) {
++res;
}
}
return res;
}
int main() {
init();
printf("%d\n", Hungarian());
return 0;
}
C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXSIZE = 510;
int n1, n2, m;
vector<bool> visited(MAXSIZE, false);
vector<int> match(MAXSIZE, 0);
vector<vector<int> > graph(MAXSIZE);
void addEdge(int from, int to) {
graph[from].push_back(to);
}
void init() {
cin >> n1 >> n2 >> m;
int u, v;
while (m--) {
cin >> u >> v;
addEdge(u, v);
}
}
bool find(int u) {
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
if (!match[v] || find(match[v])) {
match[v] = u;
return true;
}
}
}
return false;
}
int Hungarian() {
int res = 0;
for (int u = 1; u <= n1; ++u) {
fill(visited.begin(), visited.end(), false);
if (find(u)) {
++res;
}
}
return res;
}
int main() {
init();
cout << Hungarian() << endl;
return 0;
}
Go
package main
import "fmt"
type Edge struct {
to int
next *Edge
}
var (
n1, n2, m int
visited []bool
match []int
graph []*Edge
)
func addEdge(from, to int) {
edge := &Edge{to: to, next: graph[from]}
graph[from] = edge
}
func init() {
fmt.Scan(&n1, &n2, &m)
graph = make([]*Edge, n1+1)
match = make([]int, n2+1)
var u, v int
for i := 0; i < m; i++ {
fmt.Scan(&u, &v)
addEdge(u, v)
}
}
func find(u int) bool {
for p := graph[u]; p != nil; p = p.next {
v := p.to
if !visited[v] {
visited[v] = true
if match[v] == 0 || find(match[v]) {
match[v] = u
return true
}
}
}
return false
}
func Hungarian() (res int) {
for u := 1; u <= n1; u++ {
visited = make([]bool, n2+1)
if find(u) {
res++
}
}
return res
}
func main() {
fmt.Println(Hungarian())
}