最小费用最大流模板 poj 2159 模板水题

本文深入探讨了游戏开发领域的核心技术,包括游戏引擎、动画、3D空间视频等关键概念及其实现方法,旨在帮助开发者提升游戏开发技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Going Home
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 15944 Accepted: 8167

Description

On a grid map there are n little men and n houses. In each unit time, every little man can move one unit step, either horizontally, or vertically, to an adjacent point. For each little man, you need to pay a $1 travel fee for every step he moves, until he enters a house. The task is complicated with the restriction that each house can accommodate only one little man.

Your task is to compute the minimum amount of money you need to pay in order to send these n little men into those n different houses. The input is a map of the scenario, a '.' means an empty space, an 'H' represents a house on that point, and am 'm' indicates there is a little man on that point.

You can think of each point on the grid map as a quite large square, so it can hold n little men at the same time; also, it is okay if a little man steps on a grid with a house without entering that house.

Input

There are one or more test cases in the input. Each case starts with a line giving two integers N and M, where N is the number of rows of the map, and M is the number of columns. The rest of the input will be N lines describing the map. You may assume both N and M are between 2 and 100, inclusive. There will be the same number of 'H's and 'm's on the map; and there will be at most 100 houses. Input will terminate with 0 0 for N and M.

Output

For each test case, output one line with the single integer, which is the minimum amount, in dollars, you need to pay.

Sample Input

2 2
.m
H.
5 5
HH..m
.....
.....
.....
mm..H
7 8
...H....
...H....
...H....
mmmHmmmm
...H....
...H....
...H....
0 0

Sample Output

2
10
28

Source

 
题意:

给定一个N*M的地图,地图上有若干个man和house,且man与house的数量一致。man每移动一格需花费$1(即单位费用=单位距离),一间house只能入住一个man。现在要求所有的man都入住house,求最小费用。

man可以从house上跨过
 
思路:
 
模板题   建图之后 直接套最小费用流模板
 
#include <stdio.h>
#include <iostream>
#include <string.h>
#include<cmath>
using namespace std;
const int N=300;
const int MAXE=200000;
const int inf=1<<30;
int head[N],ep;
int d[N],pre[N];
bool vis[N];
int q[MAXE];
struct Edge
{
    int u,v,c,w,next;
}edge[MAXE];
void addedge(int u,int v,int w,int c)//u v 费用 容量
{
    edge[ep].u=u;
    edge[ep].v=v;
    edge[ep].w=w;
    edge[ep].c=c;
    edge[ep].next=head[u];
    head[u]=ep++;
    edge[ep].v=u;
    edge[ep].u=v;
    edge[ep].w=-w;
    edge[ep].c=0;
    edge[ep].next=head[v];
    head[v]=ep++;
}
int SPFA(int src,int des)
{
    int l,r;
    memset(pre,-1,sizeof(pre));
    memset(vis,0,sizeof(vis));
    for(int i=0;i<=des;i++) d[i]=inf;
    d[src]=0;
    l=0;r=0;
    q[r++]=src;
    vis[src]=1;
    while(l<r)
    {
        int u=q[l++];
        vis[u]=0;
        for(int j=head[u];j!=-1;j=edge[j].next)
        {
            int v=edge[j].v;
            if(edge[j].c>0&&d[u]+edge[j].w<d[v])
            {
                d[v]=d[u]+edge[j].w;
                pre[v]=j;
                if(!vis[v])
                {
                    vis[v]=1;
                    q[r++]=v;
                }
            }
        }
    }
    if(d[des]==inf)
        return 0;
    return 1;
}
int MCMF(int src,int des)
{
    int flow=0,ans=0;//flow是得到的最大流的值 ans得到的是最小的费用
    while(SPFA(src,des))
    {
        ans+=d[des];
        int u=des;
        int mini=inf;
        while(u!=src)
        {
            if(edge[pre[u]].c<mini)
                mini=edge[pre[u]].c;
                u=edge[pre[u]].u;
        }
        flow+=mini;
        u=des;
        while(u!=src)
        {
            edge[pre[u]].c-=mini;
            edge[pre[u]^1].c+=mini;
            u=edge[pre[u]].u;
        }
    }
    return ans;
}
///以上为模板
struct man
{
    int x;
    int y;
}M[111];
struct house
{
    int x,y;
}H[111];
char str[111];
int main()
{
    int n,m,mcnt,hcnt,i,j,src,des;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(!n&&!m) break;
        ep=0;
        memset(head,-1,sizeof(head));
        mcnt=hcnt=0;
        for(i=0;i<n;i++)
        {
            scanf("%s",str);
            for(j=0;j<m;j++)
            {
                if(str[j]=='H')
                {
                    hcnt++;
                    H[hcnt].x=i; H[hcnt].y=j;
                }
                else if(str[j]=='m')
                {
                    mcnt++;
                    M[mcnt].x=i; M[mcnt].y=j;
                }
            }
        }
        for(i=1;i<=mcnt;i++)
        {
            for(j=1;j<=hcnt;j++)
            {
                int dis=abs(M[i].x-H[j].x)+abs(M[i].y-H[j].y);
                addedge(i,mcnt+j,dis,1);
                //addedge(mcnt+j,i,dis,1);
            }
        }
        src=0;
        des=mcnt+hcnt+1;
        for(i=1;i<=mcnt;i++)
          addedge(src,i,0,1);
        for(j=1;j<=hcnt;j++)
            addedge(mcnt+j,des,0,1);
        int ans=MCMF(src,des);

        printf("%d\n",ans);
    }
    return 0;
}


### 关于网络算法的模板题目 网络是一种经典的图论算法,主要用于解决最大流、最小割等问。以下是几个常见的网络算法模板及其对应的经典目。 #### 1. 最大流 最大流是网络中最基本的问之一,通常可以通过 **Edmonds-Karp 算法** 或者 **Dinic 算法** 解决。下面是一个简单的 Edmonds-Karp 算法实现: ```python from collections import deque class Edge: def __init__(self, v, flow, rev): self.v = v self.flow = flow self.rev = rev def add_edge(u, v, capacity, graph): edge_u_to_v = Edge(v, capacity, len(graph[v])) edge_v_to_u = Edge(u, 0, len(graph[u])) graph[u].append(edge_u_to_v) graph[v].append(edge_v_to_u) def bfs(s, t, parent, graph): visited = [False] * len(graph) queue = deque([s]) visited[s] = True while queue: u = queue.popleft() for idx, edge in enumerate(graph[u]): if not visited[edge.v] and edge.flow > 0: queue.append(edge.v) visited[edge.v] = True parent[edge.v] = u if edge.v == t: return True return False def edmonds_karp(n, s, t, graph): parent = [-1] * n max_flow = 0 while bfs(s, t, parent, graph): path_flow = float('Inf') v = t while v != s: u = parent[v] path_flow = min(path_flow, graph[u][next(i for i, e in enumerate(graph[u]) if e.v == v)].flow) v = u v = t while v != s: u = parent[v] index = next(i for i, e in enumerate(graph[u]) if e.v == v) graph[u][index].flow -= path_flow graph[v][graph[u][index].rev].flow += path_flow v = u max_flow += path_flow return max_flow ``` 上述代码实现了基于 BFS 的 Edmonds-Karp 算法来求解最大流[^4]。 --- #### 2. 最小费用最大流 如果需要考虑每条边的成本,则可以使用 **SPFA** 或 **Bellman-Ford** 结合最短路径的思想来计算最小费用最大流。以下是一个 SPFA 实现的例子: ```python import heapq INF = int(1e9) def spfa_min_cost_max_flow(n, edges, start, end): adj_list = [[] for _ in range(n)] residual_graph = [[None]*n for _ in range(n)] for u, v, cap, cost in edges: adj_list[u].append((v, cap, cost)) adj_list[v].append((u, 0, -cost)) dist = [INF] * n potential = [0] * n prev_node = [-1] * n prev_edge = [-1] * n total_flow = 0 total_cost = 0 while True: pq = [] dist[start] = 0 heapq.heappush(pq, (dist[start], start)) while pq: d, node = heapq.heappop(pq) if d > dist[node]: continue for idx, (neighbor, cap, cost) in enumerate(adj_list[node]): if cap > 0 and dist[neighbor] > dist[node] + cost + potential[node] - potential[neighbor]: dist[neighbor] = dist[node] + cost + potential[node] - potential[neighbor] prev_node[neighbor] = node prev_edge[neighbor] = idx heapq.heappush(pq, (dist[neighbor], neighbor)) if dist[end] == INF: break for i in range(n): potential[i] += dist[i] flow = INF cur = end while cur != start: previous = prev_node[cur] edge_index = prev_edge[cur] flow = min(flow, adj_list[previous][edge_index][1]) cur = previous total_flow += flow total_cost += flow * potential[end] cur = end while cur != start: previous = prev_node[cur] edge_index = prev_edge[cur] adj_list[previous][edge_index] = ( adj_list[previous][edge_index][0], adj_list[previous][edge_index][1] - flow, adj_list[previous][edge_index][2] ) back_edge_index = None for j, (back_neighbor, _, _) in enumerate(adj_list[cur]): if back_neighbor == previous: back_edge_index = j break adj_list[cur][back_edge_index] = ( adj_list[cur][back_edge_index][0], adj_list[cur][back_edge_index][1] + flow, adj_list[cur][back_edge_index][2] ) cur = previous return total_flow, total_cost ``` 该代码通过调整势能函数优化了 SPFA,在处理负权边时更加高效[^5]。 --- #### 3. 经典模板题推荐 以下是几道经典的网络算法模板题,适合初学者练习: 1. **POJ 1273 Drainage Ditches**: 这是一道典型的 Edmonds-Karp 算法入门。 2. **HDU 3549 Flow Problem**: 需要使用 Dinic 算法提高效率。 3. **Codeforces Round #XXX Div.2 C**: 涉及到最小费用最大流的应用场景。 4. **LeetCode 787 Cheapest Flights Within K Stops**: 虽然不是纯网络,但可以用类似思路建模。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值