标签:uva
题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1687
题意:给你n个城市到m个海港的距离,求每个城市都有船只去的最短平均航行距离。
源点向城市建边 城市向海港 海港向汇点建边 容量为1,最后城市向海港的费用为距离
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
//************************************************************
//最小费用最大流算法
//SPFA求最短路
//邻接矩阵形式
//初始化:cap:容量,没有边为0
//cost:耗费,对称形式,没有边的也为0
//c是最小费用
//f是最大流
//*******************************************************
const int MAXN = 500;
const double INF = 0x3fffffff;
double cap[MAXN][MAXN];//容量,没有边为0
double flow[MAXN][MAXN];
//耗费矩阵是对称的,有i到j的费用,则j到i的费用为其相反数
double cost[MAXN][MAXN];//花费
int n;//顶点数目0~n-1
double f;//最大流
double c;//最小费用
int start, End;//源点和汇点
bool vis[MAXN];//在队列标志
int que[MAXN];
int pre[MAXN];
double dist[MAXN];//s-t路径最小耗费
bool SPFA()
{
int front = 0, rear = 0;
for (int u = 0; u <= n; u++)
{
if (u == start)
{
que[rear++] = u;
dist[u] = 0;
vis[u] = true;
}
else
{
dist[u] = INF;
vis[u] = false;
}
}
while (front != rear)
{
int u = que[front++];
vis[u] = false;
if (front >= MAXN)front = 0;
for (int v = 0; v <= n; v++)
{
if (cap[u][v]>flow[u][v] && dist[v]>dist[u] + cost[u][v])
{
dist[v] = dist[u] + cost[u][v];
pre[v] = u;
if (!vis[v])
{
vis[v] = true;
que[rear++] = v;
if (rear >= MAXN)rear = 0;
}
}
}
}
if (dist[End] >= INF)return false;
return true;
}
void minCostMaxflow()
{
memset(flow, 0, sizeof(flow));
memset(pre, -1, sizeof(pre));
memset(dist, 0, sizeof(dist));
c = f = 0;
while (SPFA())
{
double Min = INF;
for (int u = End; u != start; u = pre[u])
Min = min(Min, cap[pre[u]][u] - flow[pre[u]][u]);
for (int u = End; u != start; u = pre[u])
{
flow[pre[u]][u] += Min;
flow[u][pre[u]] -= Min;
}
c += dist[End] * Min;
f += Min;
}
}
//************************************************************
int main()
{
int N, M, K;
while (~scanf("%d%d", &N, &M))
{
if (N == 0 && M == 0) break;
memset(cap, 0, sizeof(cap));
memset(cost, 0, sizeof(cost));
memset(vis, false, sizeof(vis));
start = 0;
n = N + M + 2;
End = M + N + 1;
double tmp;
for (int i = 1; i <= N; i++)
cap[0][i] = 1;
for (int i = 1; i <= M; i++)
cap[i + N][N + M + 1] = 1;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
scanf("%lf", &tmp);
cost[i][j + N] = tmp;
cost[j + N][i] = -tmp;
cap[i][j + N] = 1;
}
}
minCostMaxflow();
printf("%.2lf\n", c / N + 0.001);
}
return 0;
}
版权声明:转载请注明出处。
UVA 10746 Crime Wave - The Sequel【最小费用最大流】
标签:uva
原文地址:http://blog.csdn.net/u014427196/article/details/47701827