网络流
struct edge(int to,cap,rev;)
vector<edge> G[MAX_V]; //图的邻接表表示
bool used[MAX_V]; //DFS用到的访问标记
//向图中增加一条从s到t容量为cap的边
void add_edge(int from,int to,int cap)
{
G[from].push_back((edge){to,cap,G[to].size()});
G[to].push_back((edge){from,0,G[from].size()-1});
}
int dfs(int v,int t,int f)
{
if(v==t)
return f;
used[v]=true;
for(int i=0;i<G[v].size();i++)
{
edge& e=G[v][i];
if(!used[e.to]&&e.cap>0)
{
int d=dfs(e.to,t,min(f,e.cap));
if(d>0)
{
e.cap-=d;
G[e.to][e.rev].cap+=d;
return d;
}
}
}
return 0;
}
int max_flow(int s,int t)
{
int flow=0;
for(;;)
{
memset(used,0,sizeof(used));
int f=dfs(s,t,INF);
if(f==0)
return flow;
flow+=f;
}
}
二分图
判断是否为二分图
着色法:
vector<int> G[MAX_V]
void AddEdge(int u, int v)
{
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int v,int c)
{
color[v]=c;
for(int i=0;i<G[v].size();i++)
{
int u=G[v][i];
if(color[u]==c)
return false;
if(color[u]==0&&!dfs(u,-c))
return false;
}
return true;
}
bool judge()
{
for(int i=1;i<=V;i++)
{
if(color[i]==0)
{
if(!Bi(i,1))
return false;
}
}
return true;
}
二分图最大匹配
匈牙利算法
int V;
vector<int> G[MAX_V];
int match[MAX_V];
bool used[MAX_V];
void add_edge(int u,int v)
{
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int v)
{
used[v]=true;
for(int i=0;i<G[v].size();i++)
{
int u=G[v][i];
int w=match[u]; //找到对方的匹配
if(w<0||(!used[w]&&dfs(w))) //如果对方还没有匹配||(对方的匹配还没有遍历到&&且对方的匹配可以腾出位置)
{
match[v]=u;
match[u]=v;
return true;
}
}
return false;
}
int bipartite_matching()
{
int res=0;
memset(match,-1,sizeof(match));
for(int v=1;v<=V;v++)
{
memset(used,0,sizeof(used));
if(dfs(v))
{
res++;
}
}
return res;
}
最小路径覆盖
DAG中 最小路径覆盖=原图顶点的个数-新图最大匹配数
Treasure Exploratio POJ 2594
不知道为什么 此题用邻接表会爆内存 之前用邻接表做 AC不了怀疑人生
此题还需要用floyed算法传递闭包
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAX 510
using namespace std;
int N,M;
int V;
int G[MAX][MAX];
bool used[MAX];
int match[MAX];
bool dfs(int v)
{
used[v]=true;
for(int u=1;u<=V;u++)
{
if(G[v][u])
{
int w=match[u];
if(w<0||!used[w]&&dfs(w))
{
match[u]=v;
return true;
}
}
}
return false;
}
int Hungary()
{
memset(match,-1,sizeof(match));
int res=0;
for(int i=1;i<=V;i++)
{
memset(used,0,sizeof(used));
if(dfs(i))
res++;
}
return res;
}
void floyed()
{
for(int k=1;k<=V;k++)
{
for(int i=1;i<=V;i++)
{
if(G[i][k]==1)
{
for(int j=1;j<=V;j++)
{
if(G[k][j]==1)
G[i][j]=1;
}
}
}
}
}
int main()
{
while(~scanf("%d%d",&N,&M))
{
if(M==0&&N==0)
break;
memset(G,0,sizeof(G));
V=N;
for(int i=0;i<M;i++)
{
int x,y;
scanf("%d%d",&x,&y);
G[x][y]=1;
}
floyed();
printf("%d\n",N-Hungary());
}
return 0;
}