最大流初学者的练习题
PS:BFS好像要超时,推荐写深搜
Code:(只有宽搜):
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<queue>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fod(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int inf=0x3f3f3f,N=1e4+10,M=1e5+10;
int last[N],len=0,
pre[N],rsd[N],
n,m,S,T;
struct edge {
int from,to,next,cap,flow;
edge(int from=0,int to=0,int next=0,int cap=0,int flow=0):from(from),to(to),next(next),cap(cap),flow(flow){}
}e[M];
void add_edge(int from,int to,int cap) {
e[++len]=edge(from,to,last[from],cap); last[from]=len;
}
int Bfs(int s,int t) {
memset(rsd,0,sizeof(rsd));
queue<int> q;
q.push(s);
rsd[s]=inf;
while(!q.empty()&&!rsd[t]) {
int from=q.front(); q.pop();
for(int i=last[from];i;i=e[i].next) {
int to=e[i].to;
if(!rsd[to]&&e[i].cap>e[i].flow) {
pre[to]=i;
rsd[to]=min(rsd[from],e[i].cap-e[i].flow);
q.push(to);
}
}
}
return rsd[t];
}
int EK(int s,int t) {
int maxflow=0;
while(Bfs(s,t)) {
for(int i=t;i!=s&&i;i=last[pre[i]]) {
e[pre[i]].flow+=rsd[t];
e[pre[i]^1].flow-=rsd[t];
}
maxflow+=rsd[t];
}
return maxflow;
}
int main() {
while(~scanf("%d%d",&m,&n)) {
memset(last,0,sizeof(last));
while(m--) {
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
add_edge(u,v,c);
add_edge(v,u,0);
}
printf("%d\n",EK(1,n));
}
return 0;
}
附一发dinic:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<queue>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fod(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int inf=0x3f3f3f,N=1e4+10,M=1e5+10;
int last[N],len=0,
vis[N],dis[N],
n,m,s,t,
cur[N];
struct edge {
int from,to,next,cap,flow;
edge(int from=0,int to=0,int next=0,int cap=0,int flow=0):from(from),to(to),next(next),cap(cap),flow(flow){}
}e[M];
void add_edge(int from,int to,int cap) {
e[++len]=edge(from,to,last[from],cap); last[from]=len;
}
int bfs() {
memset(vis,0,sizeof(vis));
queue<int>q; q.push(s);
dis[s]=0; vis[s]=1;
while(!q.empty()) {
int from=q.front() ; q.pop() ;
for(int i=last[from];i;i=e[i].next) {
if(!vis[e[i].to]&&e[i].cap>e[i].flow) {
vis[e[i].to]=1;
dis[e[i].to]=dis[from]+1;
q.push(e[i].to);
}
}
}
return vis[t];
}
int dfs(int from,int a) {
if(from==t||a==0) return a;
int flow=0,f;
for(int i=cur[from];i;i=e[i].next) {
if(dis[from]+1==dis[e[i].to]&&(f=dfs(e[i].to,min(a,e[i].cap-e[i].flow)))>0) {
e[i].flow+=f;
e[i^1].flow-=f;
flow+=f;
a-=f;
if(a==0) break;
}
}
return flow;
}
int Dinic() {
int maxflow=0;
while(bfs()) {
fo(i,1,n) cur[i]=last[i];
maxflow+=dfs(s,inf);
}
return maxflow;
}
int main() {
while(~scanf("%d%d",&m,&n)) {
memset(last,0,sizeof(last)) ;
s=1;t=n;
while(m--) {
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
add_edge(u,v,c);
add_edge(v,u,0);
}
printf("%d\n",Dinic());
}
return 0;
}