UVa 1658 Admiral (minimum cost maximum flow)

Source: Internet
Author: User

Split charge Flow

---------------------------------------------------------------------

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <vector>#define REP (i,n) for (int i=0;i<n;++i)#define CLR (x,c) memset (x,c,sizeof (x) )using namespace std;const int maxn=2000+5;const int inf=0x3f3f3f3f;struct Edge {int from,to,cap,flow,cost;};struct MCMF {bool INQ[MAXN];int D[MAXN];int A[MAXN];int P[MAXN];int n,s,t;vector<int> G[MAXN];vector<edge> edges;void init (int n) {this->n=n;Rep (I,n) g[i].clear ();edges.clear ();}void Addedge (int u,int v,int cap,int cost) {Edges.push_back (Edge) {u,v,cap,0,cost});Edges.push_back (Edge) {v,u,0,0,-cost});G[u].push_back (Edges.size ()-2);G[v].push_back (Edges.size ()-1);}bool SPFA (int &flow,int &cost) {CLR (d,inf); CLR (inq,0) ;d[s]=0; inq[s]=1; p[s]=0; A[s]=inf ;queue<int> Q;Q.push (s);While (!q.empty ()) {int X=q.front (); Q.pop ();inq[x]=0;Rep (I,g[x].size ()) {Edge &e=edges[g[x][i]];if (d[e.to]>d[x]+e.cost && e.cap>e.flow) {D[e.to]=d[x]+e.cost;P[e.to]=g[x][i];a[e.to]=min (a[x],e.cap-e.flow);if (!inq[e.to]) {Q.push (e.to); inq[e.to]=1;}}}}if (D[t]==inf) return false;Flow+=a[t];Cost+=d[t]*a[t];int x=t;While (x!=s) {Edges[p[x]].flow+=a[t];Edges[p[x]^1].flow-=a[t];X=edges[p[x]].from;}return true;}int mincost (int s,int t) {this->s=s; this->t=t;int flow=0,cost=0;while (SPFA (Flow,cost));return cost;}} g;int main (){//freopen ("test.in", "R", stdin);//freopen ("Test.out", "w", stdout);int n,m;while (scanf ("%d%d", &n,&m) ==2) {G.init (n*2+1);int a,b,c;While (m--) {scanf ("%d%d%d", &a,&b,&c);if (a>1 && a<n) a+=n;G.addedge (a,b,1,c);}for (int i=2;i<n;++i) G.addedge (i,i+n,1,0);G.addedge (0,1,2,0); G.addedge (n,n*2,2,0);printf ("%d\n", G.mincost (0,n*2));}return 0;}

---------------------------------------------------------------------

UVa 1658 Admiral (minimum cost maximum flow)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.