1. 程式人生 > >【模板】網路流

【模板】網路流

1.邊從2標號算起,j和j^1互為反邊。
 
2.棋盤一般都是二分圖模型,連邊注意方向!
 
3.分配限制用最大流卡流,取捨限制用最小割決策。
 

常見模型:最大匹配模型、最小割模型、最小路徑覆蓋模型

有時候需要配合二分。


Code:

#include<cstdio>
#include<algorithm>
using namespace std;
const int Sn = 10010, Sm = 1000010 *2, oo = (int)1e9;

int n,m,s,t,la[Sn],to[Sm],nx[Sm],rs[Sm],fy[Sm],dn,bn=1;
int ln[Sn],l,r,vis[Sn],V,hei[Sn],top;
int next[Sn],hd,tl,tmp,dis[Sn],il[Sn],pp[Sn],pre[Sn];
int maxflow,totfy;

void link(int u, int v, int w)
{
     bn++, to[bn] = v, rs[bn] = w, nx[bn] = la[u], la[u] = bn;
     bn++, to[bn] = u, rs[bn] = 0, nx[bn] = la[v], la[v] = bn;
}
bool bfs()
{
     vis[t] = ++V, hei[t] = 1;
     for(ln[l=r=1] = t; l <= r; l++)
	  for(int j = la[ln[l]]; j; j = nx[j])
	       if(rs[j^1] && vis[to[j]] != V)
	       {
		    hei[to[j]] = hei[ln[l]] + 1, vis[to[j]] = V;
		    ln[++r] = to[j]; if(to[j] == s) return true;
	       }
     return false;
}
int dfs(int d, int p)
{
     int flow = 0, f;
     if(d == t || p == 0) return p;
     for(int j = la[d]; j; j = nx[j])
	  if(vis[to[j]] == V && hei[to[j]] == hei[d] - 1)
	       if(rs[j] && ( f = dfs(to[j], min(p,rs[j])) ) > 0)
	       {
		    rs[j] -= f, rs[j^1] += f;
		    flow += f, p -= f;
		    if(!p) return flow;
	       }
     hei[d] = oo;
     return flow;
}
bool spfa()
{
     for(int i = 1; i <= dn; i ++) dis[i] = oo;
     dis[s] = 0, pp[s] = oo; // WA
     for(il[hd=tl=s] = true; hd; tmp=hd, hd=next[hd], next[tmp]=il[tmp]=0)
	  for(int j = la[hd], o; j; j = nx[j])
	       if(rs[j] && (o = dis[hd] + fy[j]) < dis[to[j]] && o <= dis[t])
	       {
		    dis[to[j]] = dis[hd] + fy[j], pp[to[j]] = min(pp[hd], rs[j]);
		    pre[to[j]] = j ^ 1;
		    if(!il[to[j]]) {
			 if(hd != tl && dis[to[j]] < dis[next[hd]]) next[to[j]] = next[hd], next[hd] = to[j];
			 else next[tl] = to[j], tl = to[j];  il[to[j]] = true; }
	       }
     if(dis[t] == oo) return false;
     for(int j = t; j != s; j = to[pre[j]])
	  rs[pre[j]^1] -= pp[t], rs[pre[j]] += pp[t];
     totfy += dis[t] * pp[t], maxflow += pp[t];
     return true;
}