1. 程式人生 > >poj3422 拆點法x->x'建立兩條邊+最小費用最大流

poj3422 拆點法x->x'建立兩條邊+最小費用最大流

algorithm printf eof class clas als typedef 建圖 get

/**
題目:poj3422 拆點法+最小費用最大流
鏈接:http://poj.org/problem?id=3422
題意:給定n*n的矩陣,含有元素值,初始sum=0.每次從最左上角開始出發,每次向右或者向下一格。終點是右下角。
每經過一個格子,獲取它的值,並把該格子的值變成0.問經過k次從左上角到右下角。能得到的數值和最大多少。

思路:我覺得本題元素值全是非負數。要不然不可以過。很多網上的博客代碼在有負數情況下過不了。
拆點法+最小費用最大流

建圖:
每一個格子x,拆成x,xi, x向xi連兩條邊,其一:x->xi,cap=1,cost=-wx;其二:x->xi,cap=k-1,cost=0;表示x這個格子可以經過k次,
第一次獲得值為wx,之後經過它只能獲得0.

左上角格子x,   s->x,cap=k,cost=0;
右下角格子x,   xi->t,cap=k,coste=0;

如果x的右邊的格子或者下面的格子是y,  xi->y,cap=k,cost=0;



*/ #include<iostream> #include<cstring> #include<vector> #include<map> #include<cstdio> #include<sstream> #include<algorithm> #include<queue> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const int N = 5500; struct Edge{ int from
, to, cap, flow, cost; Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} }; struct MCMF{ int n, m; vector<Edge> edges; vector<int> G[N]; int inq[N]; int d[N]; int p[N]; int a[N]; void init(int n){ this->n = n;
for(int i = 0; i <= n; i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int cap,long long cost){ edges.push_back(Edge(from,to,cap,0,cost)); edges.push_back(Edge(to,from,0,0,-cost)); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BellmanFord(int s,int t,int &flow,long long &cost){ for(int i = 0; i <= n; i++) d[i] = INF; memset(inq, 0, sizeof inq); 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 = edges[G[u][i]]; if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){ d[e.to] = d[u]+e.cost; p[e.to] = G[u][i]; a[e.to] = min(a[u],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 += (long long)d[t]*(long long)a[t]; for(int u = t; u!=s; u = edges[p[u]].from){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; } return true; } int MincostMaxflow(int s,int t,long long &cost){ int flow = 0; cost = 0; while(BellmanFord(s,t,flow,cost)); return flow; } }; int main() { int n, k; while(scanf("%d%d",&n,&k)==2) { int w, s = 0, t = n*n+1; MCMF mcmf; mcmf.init(t*2); mcmf.AddEdge(s,1,k,0); for(int i = 1; i <= n; i++){ for(int j = 1;j <= n; j++){ scanf("%d",&w); int x = (i-1)*n+j, y = x+t; mcmf.AddEdge(x,y,1,-w); mcmf.AddEdge(x,y,k-1,0); if(i==n&&j==n){ mcmf.AddEdge(y,t,k,0); } if(j+1<=n){ int m = (i-1)*n+j+1; mcmf.AddEdge(y,m,k,0); } if(i+1<=n){ int m = i*n+j; mcmf.AddEdge(y,m,k,0); } } } LL cost; mcmf.MincostMaxflow(s,t,cost); printf("%lld\n",-cost); } return 0; }

poj3422 拆點法x->x'建立兩條邊+最小費用最大流