UVa 1349 (二分图最小权完美匹配) Optimal Bus Route Design

时间:2022-09-18 15:29:40

题意:

给出一个有向带权图,找到若干个圈,使得每个点恰好属于一个圈。而且这些圈所有边的权值之和最小。

分析:

每个点恰好属于一个有向圈 就等价于 每个点都有唯一后继。

所以把每个点i拆成两个点,Xi 和 Yi ,然后求二分图最小权完美匹配(流量为n也就是满载时,就是完美匹配)。

 #include <bits/stdc++.h>

 using namespace std;

 const int maxn =  + ;
const int INF = ; 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 MFMC
{
int n, m;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn]; //是否在队列中
int d[maxn]; //Bellman-Ford
int p[maxn]; //上一条弧
int a[maxn]; //可改进量 void Init(int n)
{
this->n = n;
for(int i = ; i < n; ++i) G[i].clear();
edges.clear();
} void AddEdge(int from, int to, int cap, int cost)
{
edges.push_back(Edge(from, to, cap, , cost));
edges.push_back(Edge(to, from, , , -cost));
m = edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
} bool BellmanFord(int s, int t, int& flow, int& cost)
{
for(int i = ; i < n; ++i) d[i] = INF;
memset(inq, , sizeof(inq));
d[s] = ; inq[s] = ; p[s] = ; a[s] = INF;
queue<int> Q;
Q.push(s);
while(!Q.empty())
{
int u = Q.front(); Q.pop();
inq[u] = ;
for(int i = ; 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] = ; }
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
for(int u = t; u != s; u = edges[p[u]].from)
{
edges[p[u]].flow += a[t];
edges[p[u]^].flow -= a[t];
}
return true;
}
//需要保证初始网络中没有负权圈
int MincostMaxflow(int s, int t, int& cost)
{
int flow = ; cost = ;
while(BellmanFord(s, t, flow, cost));
return flow;
}
}g; int main()
{
//freopen("in.txt", "r", stdin); int n;
while(scanf("%d", &n) == && n)
{
g.Init(n*+);
for(int i = ; i <= n; ++i)
{
g.AddEdge(, i, , );//连接源点和X的点
g.AddEdge(i+n, n*+, , );//连接汇点和Y的点
}
for(int i = ; i <= n; ++i)
{
int j, d;
while(scanf("%d", &j) == && j)
{
scanf("%d", &d);
g.AddEdge(i, n+j, , d);
}
}
int cost, flow;
flow = g.MincostMaxflow(, n*+, cost);
if(flow < n) puts("N");
else printf("%d\n", cost);
} return ;
}

代码君