網絡流模板+費用流模板

注意tot是從1開始,邊的數量m爲點的平方,即n*n。
複雜度o(n * m * m)。
初始化memset(head,0,sizeof(head))

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const int INF=1<<29;
const int MAX_N=510;
const int MAX_M=MAX_N*MAX_N;
int head[MAX_N],ver[MAX_M],edge[MAX_M],Next[MAX_M],d[MAX_N],now[MAX_M];
int s,t,tot;
queue<int>q;
void Add(int x,int y,int z){
 ver[++tot]=y;edge[tot]=z;Next[tot]=head[x];head[x]=tot;
 ver[++tot]=x;edge[tot]=0;Next[tot]=head[y];head[y]=tot;
}
bool bfs(){
 memset(d,0,sizeof(d));
 while(!q.empty())
 q.pop();
 q.push(s);
 d[s]=1;
 now[s]=head[s];
 while(!q.empty()){
  int x=q.front();
  q.pop();
  for(int i=head[x];i;i=Next[i]){
   int y=ver[i];
   if(edge[i]&&!d[y]){
    q.push(y);
    now[y]=head[y];
    d[y]=d[x]+1;
    if(y==t)
    return true;
   }
  }
 }
 return false;
}
int dfs(int x,int flow){
 if(x==t)
 return flow;
 int rest=flow,k,i;
 for(i=now[x];i&&rest;i=Next[i]){
  int y=ver[i];
  if(edge[i]&&d[y]==d[x]+1){
   k=dfs(y,min(rest,edge[i]));
   if(!k)
   d[y]=0;
   edge[i]-=k;
   edge[i^1]+=k;
   rest-=k;
  }
 }
 now[x]=i;
 return flow-rest;
}
int dinic(){
 int flow=0,ans=0;
 while(bfs()){
  while(flow=dfs(s,INF))
  ans+=flow;
 }
 return ans;
}
發佈了62 篇原創文章 · 獲贊 6 · 訪問量 1940
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章