网络最大流
DInic
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 10005
#define MAXM 100005
#define INF 2147483647
struct queue {
int q[MAXN]; int head,tail;
queue() : head(1),tail(0) {}
void reset() {
head = 1; tail = 0;
}
void push(int x) {
q[++tail] = x;
}
int front() {
return q[head];
}
void pop() {
++head;
}
bool empty() {
return head>tail;
}
}q;
struct edge {
int v,cap,next;
}G[MAXM<<1];
int head[MAXN],cur[MAXN],step[MAXN];
int ans = 0,tot = -1;
int N,M,S,T;
inline bool bfs() {
q.reset(); q.push(S);
std::memset(step,-1,sizeof(step));
step[S] = 1;
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i=head[u];i!=-1;i=G[i].next) {
int v = G[i].v;
if(G[i].cap>0&&step[v]==-1) {
q.push(v);
step[v] = step[u] + 1;
}
}
}
return step[T]!=-1;
}
int dfs(int u,int a) {
if(u==T) return a;
int flow = 0,temp;
for(int& i=cur[u];i!=-1;i=G[i].next) {
int v = G[i].v;
if(step[u]+1==step[v]&&G[i].cap&&(temp = dfs(v,std::min(a,G[i].cap)))>0) {
flow += temp; a -= temp;
G[i].cap -= temp; G[i^1].cap += temp;
if(a==0) break;
}
}
return flow;
}
inline void dinic() {
while(bfs()) {
for(int i=1;i<=N;++i) cur[i] = head[i];
ans += dfs(S,INF);
}
}
inline void add(int u,int v,int cap) {
G[++tot].v = v; G[tot].cap = cap; G[tot].next = head[u]; head[u] = tot;
}
int main() {
int u,v,cap;
std::memset(head,-1,sizeof(head));
scanf("%d%d%d%d",&N,&M,&S,&T);
for(int i=1;i<=M;++i) {
scanf("%d%d%d",&u,&v,&cap);
add(u,v,cap); add(v,u,0);
}
dinic();
printf("%d",ans);
return 0;
}
费用流
SPFA
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define MAXN 5005
#define INF 2147483647
struct edge {
int u,v,next;
long long c,w;
}G[MAXN*20];
long long dis[MAXN],a[MAXN];
int vis[MAXN],p[MAXN],head[MAXN];
int N,M,S,T;
int tot = -1;
long long flow = 0,cost = 0;
inline void add(int u,int v,long long c,long long w) {
G[++tot].u = u; G[tot].v = v; G[tot].c = c; G[tot].w = w;
G[tot].next = head[u]; head[u] = tot;
}
inline bool Bellman_Ford() {
std::queue <int> q;
std::memset(vis,0,sizeof(vis));
for(int i=1;i<=N;++i) dis[i] = INF;
dis[S] = 0; vis[S] = 1; a[S] = INF; p[S] = INF;
q.push(S);
while(!q.empty()) {
int u = q.front(); q.pop();
vis[u] = 0;
for(int i=head[u];i!=-1;i=G[i].next) {
int v = G[i].v;
if(dis[v]>dis[u]+G[i].w&&G[i].c) {
dis[v] = dis[u] + G[i].w;
p[v] = i;
a[v] = std::min(a[u],G[i].c);
if(!vis[v]) {
q.push(v);
vis[v] = 1;
}
}
}
}
if(dis[T]==INF) return false;
flow += a[T];
cost += a[T]*dis[T];
int u = T;
while(u!=S) {
G[p[u]].c -= a[T];
G[p[u]^1].c += a[T];
u = G[p[u]].u;
}
return true;
}
int main() {
int u,v;
long long c,w;
std::memset(head,-1,sizeof(head));
scanf("%d%d%d%d",&N,&M,&S,&T);
for(int i=1;i<=M;++i) {
scanf("%d%d%lld%lld",&u,&v,&c,&w);
add(u,v,c,w); add(v,u,0,-w);
}
while(Bellman_Ford());
printf("%lld %lld",flow,cost);
return 0;
}