[BZOJ1877][SDOI2009]晨跑(费用流)

211 篇文章 0 订阅
72 篇文章 0 订阅

题目描述

传送门

题解

一看题目里两个约束条件:很显然最小费用最大流啊。
于是开始搞:
拆点xi,yi,表示入点和出点;
由于每个点只能到达一次,xi向yi连边,容量为1,费用为0;其中1和n除外,因为可以经过多次。
然后按照题目描述的建图,从起点的yi(出点)向终点的xi(入点)连边,每条边的长度即为费用。注意这里的边的容量也应该为1,因为有可能从1直接到n 233
从超级源向x1连边,从yn向超级汇连边,容量都为INF,费用为0。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int max_n=205;
const int max_N=max_n*2+2;
const int max_m=2e4+5;
const int max_M=max_n*3+max_m;
const int max_e=max_M*2;
const int INF=2e9;

int n,m,N,x,y,z,maxflow,mincost; 
int tot,point[max_N],next[max_e],v[max_e],c[max_e],remain[max_e];
int dis[max_N],last[max_N];
bool vis[max_N];
queue <int> q;

inline void addedge(int x,int y,int z,int cap){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z; remain[tot]=cap;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; c[tot]=-z; remain[tot]=0;
}
inline int addflow(int s,int t){
    int now=t,ans=INF;
    while (now!=s){
        ans=min(ans,remain[last[now]]);
        now=v[last[now]^1];
    }

    now=t;
    while (now!=s){
        remain[last[now]]-=ans;
        remain[last[now]^1]+=ans;
        now=v[last[now]^1];
    }
    return ans;
}
inline bool bfs(int s,int t){
    memset(dis,0x7f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    dis[s]=0;
    vis[s]=true;
    while (!q.empty()) q.pop();
    q.push(s);

    while (!q.empty()){
        int now=q.front(); q.pop();
        vis[now]=false;
        for (int i=point[now];i!=-1;i=next[i])
          if (dis[v[i]]>dis[now]+c[i]&&remain[i]){
            dis[v[i]]=dis[now]+c[i];
            last[v[i]]=i;
            if (!vis[v[i]]){
                vis[v[i]]=true;
                q.push(v[i]);
            }
          }
    }

    if (dis[t]>INF) return false;
    int flow=addflow(s,t);
    maxflow+=flow;
    mincost+=dis[t]*flow;
    return true;
}
inline void major(int s,int t){
    maxflow=0; mincost=0;
    while (bfs(s,t));
}

int main(){
    tot=-1;
    memset(point,-1,sizeof(point));
    memset(next,-1,sizeof(next));

    scanf("%d%d",&n,&m);
    N=n*2+2;
    addedge(1,2,0,INF);
    addedge(N-1,N,0,INF);
    addedge(1+1,1+n+1,0,INF);
    addedge(1+n,1+n+n,0,INF);
    for (int i=2;i<n;++i)
      addedge(1+i,1+n+i,0,1);
    for (int i=1;i<=m;++i){
        scanf("%d%d%d",&x,&y,&z);
        addedge(1+n+x,1+y,z,1);
    }
    major(1,N);
    printf("%d %d\n",maxflow,mincost);
}

总结

边的容量也是1!!!坑爹啊!!!
不过考虑一下以后这样的情况怎么避免出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值