poj2135-费用流&费用流模板-Farm Tour

来源:互联网 发布:淘宝店铺认证复核2017 编辑:程序博客网 时间:2024/05/17 00:08

https://vjudge.net/problem/POJ-2135
给定n个点。有m个路相互连接
要求从1出发,到达m,在从m回来,要求花费最小。并且不能通过相同的路径。
方法:设置边权的size为1,建立一个 超级源点和 超级会点。
超级源点到1 size为2.
超级汇点到 msize为2.
然后跑一次费用流。。。
这个以后用来测试板子。。

#include <iostream>#include<queue>#include<cstring>#include <cstdio>using namespace std;typedef long long ll;typedef int Type;const int N=1005;const Type inf=0x3f3f3f3f;struct edge{  int u,v;  Type cap, flow, cost;  edge() {}  edge(int from,int to,int c,int f,int co):u(from),v(to),cap(c),flow(f),cost(co){}};struct MCMF{  int n,m;  vector<edge>es;  vector<int>G[N];  int inq[N];//是否在队列中  Type d[N];//SPFA时总费用  int p[N];//上一条弧  Type a[N];//可改进量  void init(int n){    this->n=n;    for(int i=0; i<n; i++)G[i].clear();    es.clear();  }  void add_edge(int u,int v,Type cap,Type cost){    es.push_back(edge(u, v, cap, 0, cost));    es.push_back(edge(v, u, 0, 0, -cost));    m=es.size();    G[u].push_back(m-2);    G[v].push_back(m-1);  }    bool spfa(int s,int t,Type& flow,Type& cost){    memset(inq, 0, sizeof(inq));    for(int i=0; i<n; i++)d[i]=inf;    d[s]=0;inq[s]=1;p[s]=0;a[s]=inf;    queue<int>q;    q.push(s);    while(!q.empty()){      int u=q.front();q.pop();inq[u]=0;      for(int i=0; i<G[u].size(); i++){        edge& e=es[G[u][i]];        int v=e.v;        if(e.cap>e.flow && d[v]>d[u]+e.cost){ //在新流下考虑最小费用          d[v]=d[u]+e.cost;          a[v]=min(a[u], e.cap-e.flow);          p[v]=G[u][i];          if(!inq[v]){ inq[v]=1; q.push(v);}        }      }    }    if(d[t]==inf)return false;    flow+=a[t],cost+=a[t]*d[t];    int u=t;    while(u!=s){      es[p[u]].flow+=a[t];      es[p[u]^1].flow-=a[t];      u=es[p[u]].u;    }    return true;  }  Type Mincost(int s,int t){    Type flow=0, cost=0;    while(spfa(s,t,flow,cost));    return cost;  }}x;int n,m;int main(){ int a,b,c;    while(~scanf("%d%d",&m,&n)){          x.init(m+3);          x.add_edge(0,1,2,0);          for(int i=1;i<=n;i++){              scanf("%d%d%d",&a,&b,&c);              x.add_edge(a,b,1,c);              x.add_edge(b,a,1,c);          }          x.add_edge(m,m+1,2,0);           printf("%d\n",x.Mincost(0,m+1));     }    return 0;}