二分匹配,先判断是否是二分图,再求最大匹配。
模板如下:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <cctype>
#include <fstream>
#define INF 0x3f3f3f3f
#define EPS 1e-6
#define TEST cout<<"stop here"<<endl
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
//匈牙利算法模板(邻接表)
//ver 0.0.2
const int MAXV = 1000;
int V,E;
vector<int> G[MAXV];
int color[MAXV],match[MAXV];
bool vis[MAXV];
void init(int V){
memset(color,0,sizeof(color));
for(int i=0;i<V;i++){
G[i].clear();
}//初始化
}
void AddEdge(int u,int v){//建图
G[u].push_back(v);
G[v].push_back(u);
}
bool DFS_Color(int u,int c){//二分图判定——涂色
color[u] = c;
for(int i=0;i<G[u].size();i++){
if(color[G[u][i]] == c)
return false;
if(color[G[u][i]] == 0 && !DFS_Color(G[u][i],-c)){
return false;
}
}
return true;
}
bool Judge(){
for(int i=0;i<V;i++){
if(color[i] == 0){
if(!DFS_Color(i,1))
return false;
}
}
return true;//二分图判定
}
bool DFS_Match(int u){
vis[u] = true;
for(int i=0;i<G[u].size();i++){
int v = G[u][i],w = match[v];
if(w<0 || !vis[w] && DFS_Match(w)){
match[u] = v;
match[v] = u;
return true;
}
}
return false;//匈牙利算法模板
}
int MaxMatch(){
int ans = 0;
memset(match,-1,sizeof(match));
for(int u=0;u<V;u++){
if(match[u]<0){
memset(vis,false,sizeof(vis));
if(DFS_Match(u)){
ans++;
}
}
}
return ans;//最大匹配
}
void solve(){
for(int i=0;i<E;i++){
int u,v;
cin>> u >> v;
AddEdge(u-1,v-1);//依照题目,顶点从0还是1开始,本模板是从0开始的。
}
if(!Judge()){
cout<< "No" <<endl;
}
else{
cout<< MaxMatch() <<endl;
}//输入输出部分
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
while(cin>> V >> E){
init(V+1);
solve();
}
return 0;
}