最大流Dinic:
const int MAXN = 1000+100;
const int MAXM = 1000000+10;
const int INF = 1000000+10;
struct Edge{
int from, to, cap, flow, next;
}edge[MAXM];
int dist[MAXN], vis[MAXN], cur[MAXN], top, head[MAXN];
int n, m,sumflow,sink;
void init(){
top = 0;
memset(head, -1, sizeof(head));
}
void addedge(int u, int v, int w){
Edge E1 = {u, v, w, 0, head[u]};
edge[top] = E1;
head[u] = top++;
Edge E2 = {v, u, 0, 0, head[v]};
edge[top] = E2;
head[v] = top++;
}
bool BFS(int start, int End){
queue<int> Q;
memset(dist, -1, sizeof(dist));
memset(vis, 0, sizeof(vis));
while(!Q.empty()) Q.pop();
Q.push(start);
vis[start] = 1;
dist[start] = 0;
while(!Q.empty()){
int u = Q.front();
Q.pop();
for(int i = head[u]; i != -1; i = edge[i].next){
Edge E = edge[i];
if(!vis[E.to] && E.cap > E.flow){
vis[E.to] = 1;
dist[E.to] = dist[u] + 1;
if(E.to == End) return true;
Q.push(E.to);
}
}
}
return false;
}
int DFS(int x, int a, int End){
if(x == End || a == 0) return a;
int flow = 0, f;
for(int& i = cur[x]; i != -1; i = edge[i].next){
Edge& E = edge[i];
if(dist[E.to] == dist[x]+1 && (f = DFS(E.to, min(a, E.cap-E.flow), End)) > 0){
E.flow += f;
edge[i^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
int Dinic(int start, int End){
int flow = 0;
while(BFS(start, End)){
memcpy(cur, head, sizeof(head));
flow += DFS(start, INF, End);
}
return flow;
}
最小费用最大流:
const int INF = 0x3f3f3f3f;
const int MaxNode = 205;
const int MaxEdge = 40005;
struct Edge{
int to,vol,cost,next;
}Edges[MaxEdge];
int Pre[MaxNode],Path[MaxNode],Dist[MaxNode],Head[MaxNode],EdgeCount;
bool vis[MaxNode];
void addedge(int u, int v, int vol, int cost){
Edges[EdgeCount].to = v;
Edges[EdgeCount].vol = vol;
Edges[EdgeCount].cost = cost;
Edges[EdgeCount].next = Head[u];
Head[u] = EdgeCount++;
Edges[EdgeCount].to = u;
Edges[EdgeCount].vol = 0;
Edges[EdgeCount].cost = -cost;
Edges[EdgeCount].next = Head[v];
Head[v] = EdgeCount++;
}
bool Spfa(int s, int t){
memset(Dist, 0x3f3f3f3f, sizeof(Dist));
memset(Pre, -1, sizeof(Pre));
memset(vis, false, sizeof(vis));
Dist[s] = 0;
queue<int>Q;
Q.push(s);
vis[s] = true;
while (!Q.empty()){
int u = Q.front();
Q.pop();
vis[u] = false;
for (int e = Head[u]; e != -1; e = Edges[e].next){
int v = Edges[e].to;
if (Edges[e].vol > 0 && Dist[v] > Dist[u] + Edges[e].cost){
Dist[v] = Dist[u] + Edges[e].cost;
Pre[v] = u;
Path[v] = e;
if(!vis[v]){
vis[v] = true;
Q.push(v);
}
}
}
}
return Pre[t] != -1;
}
int MCMF(int s, int t){
int cost = 0;
int max_flow = 0;
int u, v, e;
while (Spfa(s, t)){
int f = INF;
for (u = t; u != s; u = Pre[u]){
f = min(f, Edges[Path[u]].vol);
}
for (u = t; u != s; u = Pre[u]){
e = Path[u];
Edges[e].vol -= f;
Edges[e^1].vol += f;
}
max_flow += f;
cost += f*Dist[t];
}
return cost;
}
void init(){
memset(Head,-1,sizeof(Head));
EdgeCount = 0;
}