#include "stdio.h" //最大流模板 poj 1273
#include "queue"
using namespace std;
int n,m;
#define N 205
#define INF 0x3fffffff
int map[N][N];
int maxf[N];
int route[N];
int MIN(int x,int y){ return x<y?x:y; }
int BFS() //BFS找一条可行流
{
int i;
for(i=1;i<=n;i++)
{
route[i] = -1;
maxf[i] = INF;
}
queue<int> q;
q.push(1);
int x,y;
while(!q.empty())
{
x = q.front();
q.pop();
for(y=1;y<=n;y++)
{
if(route[y]==-1 && map[x][y]!=0)
{
route[y] = x;
maxf[y] = MIN(maxf[x],map[x][y]);
q.push(y);
}
}
}
if(route[n]==-1) return 0;
return maxf[n];
}
int EK()
{
int ans=0,kejia;
while(kejia = BFS())
{
ans += kejia;
int x,y=n;
while(y!=1)
{
x = route[y];
map[x][y] -= kejia;
map[y][x] += kejia;
y = x;
}
}
return ans;
}
int main()
{
int i,j;
int x,y,k;
while(scanf("%d %d",&m,&n)!=-1) //m条边,n个点
{
memset(map,0,sizeof(map));
while(m--)
{
scanf("%d %d %d",&x,&y,&k); //从x到y的流量为k;
map[x][y] += k;
}
int ans = EK();
printf("%d\n",ans);
}
return 0;
}
下面是用邻接表写的,提交超时!
#include "stdio.h"
#include "string.h"
#include "queue"
using namespace std;
#define N 205
#define INF 0x3fffffff
struct node{
int u,v,w;
int next;
}edge[2*N*10];
int n,idx;
int dis[N],route[N],head[N];
int EK();
int BFS();
void init();
int MIN(int x,int y);
void adde(int u,int v,int w);
void addedge(int u,int v,int w);
int main()
{
int m;
int i,j;
int x,y,w;
while(scanf("%d %d",&m,&n)!=-1)
{
init();
while(m--)
{
scanf("%d %d %d",&x,&y,&w);
adde(x,y,w);
}
int ans = EK();
printf("%d\n",ans);
}
return 0;
}
void init()
{
idx = 0;
memset(head,-1,sizeof(head));
}
int MIN(int x,int y){ return x<y?x:y; }
void adde(int u,int v,int w)
{
addedge(u,v,w);
addedge(v,u,0);
}
void addedge(int u,int v,int w)
{
edge[idx].u = u;
edge[idx].v = v;
edge[idx].w = w;
edge[idx].next = head[u];
head[u] = idx;
idx++;
}
int BFS()
{
int i;
int x,y;
memset(route,-1,sizeof(route));
for(i=0;i<N;i++) dis[i] = INF;
queue<int> q;
q.push(1);
while(!q.empty())
{
x = q.front();
q.pop();
for(i = head[x];i!=-1;i=edge[i].next)
{
y = edge[i].v;
if(route[y]==-1 && edge[i].w)
{
route[y] = i;
dis[y] = MIN(dis[x],edge[i].w);
q.push(y);
}
}
if(route[n]!=-1) return dis[n];
}
if(route[n]==-1) return 0;
return dis[n];
}
int EK()
{
int ans = 0;
int kejia;
while(kejia = BFS())
{
ans += kejia;
int x,y=route[n];
while(y!=1 && y!=0)
{
x = y^1;
edge[y].w -= kejia;
edge[x].w += kejia;
y = route[edge[y].u];
}
}
return ans;
}