1. 程式人生 > >zkw費用流

zkw費用流

inline bool SPFA()
{
    memset(dis,0x3f,sizeof(dis));
    dis[T]=0;q.push(T);
    while(!q.empty())
    {
        int tmp=q.front();q.pop();
        b[tmp]=0;
        for(int i=head[tmp];i;i=a[i].nxt)
          if(dis[a[i].to]>dis[tmp]+a[i^1].cost&&a[i^1].remain)
          {
            dis[a[i].to
]=dis[tmp]+a[i^1].cost; if(!b[a[i].to]) b[a[i].to]=1,q.push(a[i].to); } } return dis[S]<INF; } int dfs(int now,int limit,int cost) { vis[now]=1; if(now==T||!limit) return ans2+=limit*cost,limit; int flow=0,f; for(int i=head[now];i;i=a[i].nxt) if(dis[now
]-a[i].cost==dis[a[i].to]&&a[i].remain&&!vis[a[i].to]&&(f=dfs(a[i].to,min(limit,a[i].remain),cost+a[i].cost))) { limit-=f,flow+=f,a[i].remain-=f,a[i^1].remain+=f; if(!limit) return flow; } dis[now]=-1;return flow; } inline void zkw() { while
(SPFA()) do { memset(vis,0,sizeof(vis)); ans1+=dfs(S,INF,0); } while(vis[T]); }