wojkxlq 发表于 2015-9-20 14:25:14

庄立 的SAP网络流模板

  http://acm.hdu.edu.cn/showproblem.php?pid=3549


View Code


#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedefstruct {int v,next,val;} edge;
const int MAXN=20010;
const int MAXM=500010;
edge e;
int p,eid;
inline void init(){memset(p,-1,sizeof(p));eid=0;}
//有向
inline void insert1(int from,int to,int val)
{
e.v=to;
e.val=val;
e.next=p;
p=eid++;
swap(from,to);
e.v=to;
e.val=0;
e.next=p;
p=eid++;
}
//无向
inline void insert2(int from,int to,int val)
{
e.v=to;
e.val=val;
e.next=p;
p=eid++;
swap(from,to);
e.v=to;
e.val=val;
e.next=p;
p=eid++;
}
int n,m;//n为点数 m为边数
int h;
int gap;
int source,sink;
inline int dfs(int pos,int cost)
{
if (pos==sink)
{
return cost;
}
int j,minh=n-1,lv=cost,d;
for (j=p;j!=-1;j=e.next)
{
int v=e.v,val=e.val;
if(val>0)
{
if (h+1==h)
{
if (lv<e.val) d=lv;
else d=e.val;
d=dfs(v,d);
e.val-=d;
e.val+=d;
lv-=d;
if (h>=n) return cost-lv;
if (lv==0) break;
}
if (h<minh)    minh=h;
}
}
if (lv==cost)
{
--gap];
if (gap]==0) h=n;
h=minh+1;
++gap];
}
return cost-lv;
}
int sap(int st,int ed)
{
source=st;
sink=ed;
int ret=0;
memset(gap,0,sizeof(gap));
memset(h,0,sizeof(h));
gap=n;
while (h<n)
{
ret+=dfs(st,INT_MAX);
}
return ret;
}

int main()
{
int t,add=1;
scanf("%d",&t);
while(t--)
{
printf("Case %d: ",add++);
scanf("%d%d",&n,&m);
init();
int i;
int ll,rr,cap;
for(i=0;i<m;i++)
{
scanf("%d%d%d",&ll,&rr,&cap);
insert1(ll,rr,cap);
}
printf("%d\n",sap(1,n));
}
return 0;
}
页: [1]
查看完整版本: 庄立 的SAP网络流模板