最小(大)费用流

算法很简单 Spfa+增广路
1、首先按照边的费用Spfa最短路(如果是求最大费用可用最长路)
2、接着增光路的可行流的调节
3、重复1 2 直到最短路无法到达汇点为止

挺简单的注意细节即可

Poj 3422
这题的建图很精妙 赞
/*
* this code is made by LinMeiChen
* Problem:
* Type of Problem:
* Thinking:
* Feeling:
*/
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<string>
#include<vector>
#include<queue>
#include<list>
using namespace std;
typedef long long lld;
typedef unsigned int ud;
#define INF_MAX 0x3f3f3f3f
#define eatline() char chch;while((chch=getchar())!='\n')continue;
#define MemsetMax(a) memset(a,0x3f,sizeof a)
#define MemsetZero(a) memset(a,0,sizeof a)
#define MemsetMin(a) memset(a,-1,sizeof a)
#define MemsetFalse(a) MemsetZero(a)
#define PQ priority_queue
#define Q queue
#define maxn 5010
#define maxm 100008
struct Edge
{
int v, f, c, next;
}E[maxm];
int cnt;
int head[maxn];
int map[55][55];
int dis[maxn], mark[maxn], pre[maxn];


bool Spfa(int s, int t)
{
fill(dis, dis + maxn, INF_MAX);
memset(mark, 0, sizeof mark);
memset(pre, -1, sizeof pre);
Q<int>q;
q.push(s);
dis[s] = 0;
mark[s] = 1;
while (!q.empty())
{
int u = q.front(); q.pop();
mark[u] = 0;
for (int i = head[u]; i != -1; i = E[i].next)
{
int v = E[i].v;
if (E[i].f>0 && dis[v] > dis[u] + E[i].c)
{
pre[v] = i;
dis[v] = dis[u] + E[i].c;
if (!mark[v])
{
q.push(v);
mark[v] = 1;
}
}
}
}
return dis[t] != INF_MAX;
}


int argument(int s, int t)
{
int minflow = INF_MAX;
int maxflow = 0;
for (int i = pre[t]; i!= -1; i = pre[E[i ^ 1].v])
{
minflow = min(minflow, E[i].f);
}
for (int i = pre[t]; i!= -1; i = pre[E[i ^ 1].v])
{
E[i].f -= minflow;
E[i ^ 1].f += minflow;
maxflow += E[i].c;
}
return maxflow;
}


int maxcostflow(int s, int t)
{
int maxflow = 0;
while (Spfa(s, t))
maxflow += argument(s, t);
return maxflow;
}


void add_edge(int u, int v, int f, int c)
{
E[cnt].v = v;
E[cnt].f = f;
E[cnt].c = c;
E[cnt].next = head[u];
head[u] = cnt++;


E[cnt].v = u;
E[cnt].f = 0;
E[cnt].c = -c;
E[cnt].next = head[v];
head[v] = cnt++;
}


int main()
{
int n, k;
while (scanf("%d%d", &n, &k) != EOF)
{
memset(head, -1, sizeof head);
cnt = 0;
int s = 2*n*n+1, t = s + 1;
for (int i = 1; i <= n;i++)
for (int j = 1; j <= n; j++)
scanf("%d", &map[i][j]);
for (int i = 1; i <= n;i++)
for (int j = 1; j <= n; j++)
{
int u = (n*(i - 1) + j - 1)*2;
int v = u + 1;
add_edge(u, v, 1, -map[i][j]);
add_edge(u, v, k - 1, 0);
}
for (int i = 1; i <= n;i++)
for (int j = 1; j < n; j++)
{
int u = (n*(i - 1) + j -1)*2 + 1;
int v = u + 1;
add_edge(u, v, k, 0);
}
for (int i = 1; i < n;i++)
for (int j = 1; j <= n; j++)
{
int u = (n*(i - 1) + j - 1)*2 + 1;
int v = u + 2 * n - 1;
add_edge(u, v, k, 0);
}
add_edge(s, 0, k, 0);
add_edge(2*n*n-1, t, k, 0);
printf("%d\n", -maxcostflow(s, t));
}
return 0;
}

你可能感兴趣的:(算法,网络,poj)