HDU 6118 度度熊的交易计划 (最小费用最大流模板题)

题目链接

度度熊的交易计划

分析

这是一个最小费用最大流的模板题,建边也很直接,唯一需要注意的是当跑出来的费用为正(dist[t]>0)的时候就不要跑了,当时就是这个地方弄错了,还以为我的模板错啦…..

AC code

/*Problem : 6118 ( 度度熊的交易计划 )     Judge Status : Accepted
*RunId : 21751738    Language : G++    Author : zouzhitao
*Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
*/
#include
#define pb push_back
#define mp make_pair
#define PI acos(-1)
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define INF64 0x3f3f3f3f3f3f3f3f
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define ms(x,v) memset((x),(v),sizeof(x))
#define scint(x) scanf("%d",&x );
#define scf(x) scanf("%lf",&x );
#define eps 1e-10
#define dcmp(x) (fabs(x) < eps? 0:((x) <0?-1:1))
#define lc o<<1
#define rc o<<1|1
using namespace std;
typedef long long LL;
typedef long double DB;
typedef pair<int,int> Pair;
const int maxn = 500+10;
const int MAX_V= 500+10;

int a[maxn],b[maxn],c[maxn],d[maxn];

struct Edge{
  int from,to,cap,cost;
  Edge(int f,int t,int c,int co):from(f),to(t),cap(c),cost(co){}
};
std::vector E;
std::vector<int> G[MAX_V];
void add_edge(int u,int v,int cap,int cost){
  E.push_back(Edge(u,v,cap,cost));G[u].push_back(E.size()-1);
  E.push_back(Edge(v,u,0,-cost)) ;G[v].push_back(E.size()-1);
}
struct MCMF{
  int dist[MAX_V];
  int pre_E[MAX_V];//最短路径弧
  bool inq[MAX_V];//spfa判断
  //未判断负圈
  void spfa(int s){
    memset(dist,INF,sizeof(dist));
    memset(inq,false,sizeof(inq));
    queue<int> Q;
    Q.push(s);
    dist[s] = 0;
    inq[s] = true;
    pre_E[s] = -1;
    while(!Q.empty())
    {
      int u = Q.front();Q.pop();
      inq[u] = false;
      for(int i=0 ; iif(e.cap>0&&dist[e.to]>dist[u]+e.cost){
          dist[e.to] = dist[u]+e.cost;
          pre_E[e.to] = G[u][i];
          if(!inq[e.to]){Q.push(e.to);inq[e.to] = true;}
        }
      }
    }
  }

  int min_cost_flow(int s,int t,int f){
    int res = 0;
    while (f>0) {
      spfa(s);
      if(dist[t]>0)break;//不能增广
      //沿着最短路增广
      int d = f;
      for(int i = pre_E[t] ; i!=-1 ;i = pre_E[E[i].from])d = min(d,E[i].cap);
      f-=d;
      res+=d*dist[t];
      for(int i = pre_E[t] ; i!=-1 ;i = pre_E[E[i].from]){
        E[i].cap-=d;
        E[i^1].cap+=d;
      }
    }
    return res;
  }
};

MCMF flow;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n,m;
    while (cin>>n >> m) {
        E.clear();
        for(int i=0 ; i<=n+1 ; ++i)G[i].clear();
        for(int i=1 ; i<=n ; ++i)cin>>a[i]>>b[i]>>c[i]>>d[i];
        for(int i=0 ; iint u,v,x;cin>>u>>v >> x;
            if(u == v)continue;
            add_edge(u,v,INF,x);
            add_edge(v,u,INF,x);
        }
        int s = 0,t =n+1;
        for(int i=1 ; i<=n ; ++i){
            add_edge(s,i,b[i],a[i]);
            add_edge(i,t,d[i],-c[i]);
        }
        int ans = flow.min_cost_flow(s,t,INF);
        std::cout << max(0,-ans) << '\n';
    }
    return 0;
}

你可能感兴趣的:(算法刷题)