uva 12092 Paint the Roads
题目大意:某国有n个城市,用m条单向道路相连。你的任务是粉刷其中一些道路,使得被粉刷的道路组成一些没有公共边的回路,且每个城市恰好要在其中的k条回路上。被粉刷的所有道路的总长度要尽量小。求最小粉刷长度。
解题思路:将每个城市拆成a, b两个点。设置超级源点,连向所有城市的a点,容量为k,费用为0。设置超级汇点,使所有城市的b点连向超级汇点,容量为k,费用为0。然后如果i城市和j城市之间有道路,则由i城市的a点向j城市的b点连边,容量为1,费用为这条道路的长度。这样建图,可以把a点当成是出度,b点当成是入度。在图中若每个点的入度都等于出度等于k,则图中每个点都在k个回路上。上图跑最大流,若满流则可以满足条件,输出最小费,若不能满流,则输出-1。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 500;
const int M = 5000;
const int INF = 0x3f3f3f3f;
int n, m, k, s, t;
int pre[N], inq[N];
ll a[N], d[N];
struct Edge{
int from, to;
ll cap, flow;
ll cos;
};
vector<Edge> edges;
vector<int> G[M];
void init() {
for (int i = 0; i <= m * 2; i++) G[i].clear();
edges.clear();
}
void addEdge(int from, int to, ll cap, ll cos) {
edges.push_back((Edge){from, to, cap, 0, cos});
edges.push_back((Edge){to, from, 0, 0, -cos});
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
int BF(int s, int t, ll& flow, ll& cost) {
queue<int> Q;
memset(inq, 0, sizeof(inq));
memset(a, 0, sizeof(a));
memset(pre, 0, sizeof(pre));
for (int i = 0; i < N; i++) d[i] = INF;
d[s] = 0;
a[s] = INF;
inq[s] = 1;
pre[s] = 0;
Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
inq[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] > d[u] + e.cos) {
d[e.to] = d[u] + e.cos;
a[e.to] = min(a[u], e.cap - e.flow);
pre[e.to] = G[u][i];
if (!inq[e.to]) {
inq[e.to] = 1;
Q.push(e.to);
}
}
}
}
if (d[t] == INF) return 0;
flow += a[t];
cost += (ll)d[t] * (ll)a[t];
for (int u = t; u != s; u = edges[pre[u]].from) {
edges[pre[u]].flow += a[t];
edges[pre[u]^1].flow -= a[t];
}
return 1;
}
int MCMF(int s, int t, ll& cost) {
ll flow = 0;
cost = 0;
while (BF(s, t, flow, cost));
return flow;
}
void input() {
scanf("%d %d %d", &n, &m, &k);
s = 2 * n + 1, t = 2 * n + 2;
int u, v, d;
for (int i = 0; i < n; i++) {
addEdge(s, i, k, 0);
addEdge(i + n, t, k, 0);
}
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &u, &v, &d);
addEdge(u, v + n, 1, d);
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
init();
input();
ll cost;
int cap = MCMF(s, t, cost);
if (cap < n * k) printf("-1\n");
else printf("%lld\n", cost);
}
return 0;
}