最大匹配
- 最大匹配
- 最小點覆蓋 = 最大匹配
- 最大獨立集 = N - 最大匹配(在二分圖中(求一個最大的集合,使集合中的兩兩不存在 ))
- 最少邊覆蓋 = N(原圖節點數) - 最大匹配數。
鄰接表:
/*
求 N ,M 的最大匹配
*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<vector>
using namespace std;
const int maxn = 105;
bool Used[maxn];
int Match[maxn];
vector<int> G[maxn + 5];
int N, M;
// 找增廣路
/*
過程 就是 集合A中的某點, 到集合B中的某點 是否有增廣路
有的意思就是說,可以形成新的匹配,
沒有就是會說:這個點 到另一個點 無法形成匹配然後換集合B中的點
B中的點全換完 也沒有找到增廣路,那A中這個點 就沒有匹配。
*/
bool Find(int x){
for (int i = 0; i < G[x].size(); ++i) {
int v = G[x][i];
if(Used[v] == 0){
Used[v] = 1;
if (Match[v] == -1 || Find(Match[v])) {
Match[v] = x;
return true;
}
}
}
return false;
}
int main (){
while(~scanf("%d%d", &N, &M)){
int n, tmp;
memset(G, 0, sizeof(G));
memset(Match, -1, sizeof(Match));
for(int i = 1; i <= M; ++i){
scanf("%d", &n);
for(int j = 1; j <= n; ++j){
scanf("%d", &tmp);
G[i].push_back(tmp);
}
}
int Ans = 0;
for (int i = 1; i <= M; ++i) {
memset(Used, 0, sizeof(Used));
if (Find(i)) {
Ans += 1;
}
}
printf("%d\n", Ans);
}
return 0;
}
鄰接矩陣:
/*
求 最小點覆蓋
*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<vector>
using namespace std;
const int maxn = 105;
bool Used[maxn];
int Match[maxn];
int G[maxn + 5][maxn + 5];
int N, M, K;
// 找增廣路
/*
過程 就是 集合A中的某點, 到集合B中的某點 是否有增廣路
有的意思就是說,可以形成新的匹配,
沒有就是會說:這個點 到另一個點 無法形成匹配然後換集合B中的點
B中的點全換完 也沒有找到增廣路,那A中這個點 就沒有匹配。
*/
bool Find(int x){
for (int i = 0; i < M; ++i) {
if(G[x][i] && Used[i] == 0){
Used[i] = 1;
if (Match[i] == -1 || Find(Match[i])) {
Match[i] = x;
return true;
}
}
}
return false;
}
int main (){
while(~scanf("%d", &N) && N){
scanf("%d%d", &M, &K);
int n, m;
memset(G, 0, sizeof(G));
memset(Match, -1, sizeof(Match));
for(int i = 1; i <= K; ++i){
scanf("%d%d", &n, &m);
if(n && m)
G[n][m] = 1;
}
int Ans = 0;
for (int i = 0; i < N; ++i) {
memset(Used, 0, sizeof(Used));
if (Find(i)) {
Ans += 1;
}
}
printf("%d\n", Ans);
}
return 0;
}