模板参考Kuangbin的模板
以下是数据结构部分:
struct Edge
{
int to,next;
}edge[maxn];
//to 是该边指向的点 next是这个点上次用的边的编号,用来找到这个点上次和其他点维持的边关系 edge的下标代表边的编号
int head[maxn],tot;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}//初始化函数
void addedge(int u,int v)
{
edge[tot].to=v;//对边进行编号
edge[tot].next=head[u];//将U这个点上一次连接的点记录如果没有即为-1
head[u]=tot++;//等于边的编号,之后edge[head[u]]即可调用这个边
}//加边函数
主要注意和思考的地方是addedge()函数,我们先假设u和v点分别代表二分图的左边的点集和右边的点集,addedge()函数是我们建立边的一个函数。 init()初始化函数一定要放在addedge()开始
edge[tot].to=v;这句话对边进行编号, 编号为tot 的这条边对应的v点是v
edge[tot].next=head[u]; 将u这个点上一次连接的点记录如果没有即为-1
我们先假设 1 2点关联,此时编号为0的边就是1 2的边, 我们再 1 3关联的时候,会发现编号为1的边是1 3的边,此时next就会指向编号1。也就是说方便了我们到时候遍历和1关联的点。
head[u] 更新下次如果还是这个u时记录的边的编号
上代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=50010;//边数的最大值
struct Edge
{
int to,next;
}edge[maxn];
//to 是该边指向的点 next是这个点上次用的边的编号,用来找到这个点上次和其他点维持的边关系 edge的下标代表边的编号
int head[maxn],tot;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}//初始化函数
void addedge(int u,int v)
{
edge[tot].to=v;//对边进行编号
edge[tot].next=head[u];//将U这个点上一次连接的点记录如果没有即为-1
head[u]=tot++;//等于边的编号,之后edge[head[u]]即可调用这个边
}//加边函数
int linker[maxn];
bool used[maxn];
int uN;
bool dfs(int u)
{
for(int i=head[u];i!=-1;i = edge[i].next)//顺着边过去,一直遍历和这个点连接过的点和边
{
int v=edge[i].to;
if(!used[v])
{
used[v]=true;
if(linker[v]==-1 || dfs(linker[v]))
{
linker[v]=u;
return true;
}
}
}
return false;
}
int hungary()
{
int res=0;
memset(linker,-1,sizeof(linker));
for(int u=0;u<uN;u++)
{
memset(used,false,sizeof(used));
if(dfs(u)) res++;
}
return res;
}
int main ()
{
}
算法思想:https://blog.youkuaiyun.com/kirito9943/article/details/81448179
二分图最大匹配(匈牙利算法)邻接矩阵版链接:https://blog.youkuaiyun.com/kirito9943/article/details/81436014