染色法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int h[N], ne[N], e[N], idx;
int color[N];
int n, m;
//用邻接表存储图
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
bool dfs(int u, int c)
{
color[u] = c;
//遍历当前这点的所有邻点
for(int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if(!color[j])
{
if(!dfs(j, 3 - c)) return false;
}
else if(color[j] == c) return false; //一条边相连的两点怎么能是相同的颜色呢
}
return true;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m -- )
{
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
bool flag = true;
for(int i = 1; i <= n; i ++ )
{
if(!color[1])
{
if(!dfs(1, 1))
{
flag = false;
break;
}
}
}
if(flag) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
匈牙利算法:给定一个二分图,求最大匹配
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 10010;
int match[N];
bool st[N];
int h[N], e[M], ne[M], idx;
int n1, n2, m;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
bool find(int x)
{
for(int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if(!st[j])
{
st[j] = true;
if(match[j] == 0 || find(match[j])) return true;
}
}
return false;
}
int main()
{
cin >> n1 >> n2 >> m;
while (m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
}
int res = 0;
for(int i = 1; i <= n1; i ++ )
{
memset(st, false, sizeof st);
if(find(i)) res ++ ;
}
cout << res << endl;
return 0;
}