UVA10806 题解

前言

题目传送门!

更好的阅读体验?

费用流简单题。

思路

数据范围这么小,也肯定不是让你跑 Dijkstra 之类的。

考虑费用流。建立一个超级源点 \(S\),连边 \(S \xrightarrow{cap = 1 \ cost = 0} 1\),表示要来回两次。

然后直接建图,对于图中的两个点 \((u, v)\),建双向\(u \xrightarrow{cap = 1 \ cost = w} v\),原因显然。

然后跑板子即可。如果最后的流量不是 \(2\),说明不能跑满来回这两次。输出无解。

否则输出代价即可。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 105, inf = 0x3f3f3f3f;
struct Edge {int now, nxt, w, cost;} e[114514];
int head[N], cur = 1;
void ad(int u, int v, int  w, int cost)
{
    e[++cur].now = v, e[cur].nxt = head[u], e[cur].w = w, e[cur].cost = cost;
    head[u] = cur;
}
void add(int u, int v, int w, int cost) {ad(u, v, w, cost), ad(v, u, 0, -cost);}
int dis[N], icost[N], pre[N]; bool inque[N];
int s, t;
bool spfa()
{
    queue <int> q;
    memset(dis, 0x3f, sizeof dis), memset(icost, 0, sizeof icost);
    q.push(s), dis[s] = 0, icost[s] = inf, inque[s] = true;
    while (!q.empty())
    {
        int u = q.front();
        q.pop(), inque[u] = false;
        for (int i = head[u]; i; i = e[i].nxt)
        {
            int v = e[i].now;
            if (!e[i].w) continue;
            if (dis[u] + e[i].cost < dis[v])
            {
                dis[v] = dis[u] + e[i].cost, pre[v] = i;
                icost[v] = min(icost[u], e[i].w);
                if (!inque[v]) q.push(v), inque[v] = true;
            }
        }
    }
    return icost[t] > 0;
}
void EK(int &flow, int &cost)
{
    while (spfa())
    {
        int w = icost[t];
        flow += w, cost += w * dis[t];
        for (int i = t; i != s; i = e[pre[i] ^ 1].now)
            e[pre[i]].w -= w, e[pre[i] ^ 1].w += w;
    }
}
void solve()
{
	memset(head, 0, sizeof head), cur = 1;
    int n, m;
	scanf("%d%d", &n, &m);
    if (n == 0) exit(0);
    
	s = 0, t = n; add(s, 1, 2, 0);
	while (m--)
	{
		int u, v, w;
		scanf("%d%d%d", &u, &v, &w);
		add(u, v, 1, w), add(v, u, 1, w);
	}
	int flow = 0, cost = 0; EK(flow, cost);
	if (flow != 2) puts("Back to jail"); else cout << cost << '\n';
}
int main()
{
	while (true) solve();
	return 0;
}
posted @ 2023-02-01 17:30  liangbowen  阅读(24)  评论(0编辑  收藏  举报