题目链接
题意
n点m条边的无向图,每个点的点权是ai,没经过一次点,点权增加bi,即第k次经过i点权值为ai + (k - 1) * bi,现给出q个xi和q个yi,每次从中选出一组xi,yi,统计从xi到yi的代价和(代价为从xi到yi经过的所有点的点权和),每个点只能选一次,q次后(也就是全选完),求最小代价。
思路
考虑最小费用最大流。
重点解决几个问题:
①点权改边权。拆点,一个点拆成一个入点和一个出点,点权就改为了从入点到出点的边权。
②每经过一次点,权值增加。在网络流里,可以用拆点,入点和出点间的容量为1来限制该点只能走一次,那么如果要限制走q次,可以从入点到出点连q条边,容量为1,费用为ai,ai+bi,ai+2*bi…
③q组起点和终点每个点只能选一次。建一个超级源点S和一个超级汇点T,从S到每个xi连一条容量为1的边,yi到T连一条容量为1的边,这样就可以保证每个点只选一次。
#include
#define INF 0x3f3f3f3f
using namespace std;
const int N = 5e3 + 7;
const int M = 1e4 + 7;
const int maxn = 5e3 + 7;
typedef long long ll;
int maxflow, mincost;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int ca, int f, int co):from(u), to(v), cap(ca), flow(f), cost(co){};
};
struct MCMF
{
int n, m, s, t;
vector<Edge> edges;
vector<int> G[N];
int inq[N], d[N], p[N], a[N];//是否在队列 距离 上一条弧 可改进量
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void add(int from, int to, int cap, int cost) {
edges.push_back(Edge(from, to, cap, 0, cost));
edges.push_back(Edge(to, from, 0, 0, -cost));
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool SPFA(int s, int t, int &flow, int &cost) {
for (int i = 0; i < N; i++) d[i] = INF;
memset(inq, 0, sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
inq[u]--;
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.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]) {
inq[e.to]++;
que.push(e.to);
}
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int MinMaxflow(int s, int t) {
int flow = 0, cost = 0;
while (SPFA(s, t, flow, cost));
maxflow = flow; mincost = cost;
return cost;
}
};
int main()
{
int n, m, s, t, q, S, T;
scanf("%d%d%d", &n, &m, &q);
MCMF solve;
S = 0, T = 2 * n + 1;
for (int i = 1, x, y; i <= n; i++) {
scanf("%d%d", &x, &y);
for (int j = 1; j <= q; j++) {//拆点,建q条边,每个点最多走q次
solve.add(i, i + n, 1, x + y * (j - 1));//i是入点,i+n是出点
}
}
for (int i = 1, x, y; i <= m; i++) {
scanf("%d%d", &x, &y);
solve.add(x + n, y, INF, 0);//原图的边就从出点到入点,容量为INF,费用为0,因为点权用拆点的边来表示了
solve.add(y + n, x, INF, 0);//无向图,建反向边
}
for (int i = 1, x; i <= q; i++)//从源点到xi建容量为1,费用为0的边
scanf("%d", &x), solve.add(S, x, 1, 0);
for (int i = 1, x; i <= q; i++)//从yi到T建容量为1,费用为0的边
scanf("%d", &x), solve.add(x + n, T, 1, 0);
solve.MinMaxflow(S, T);
printf("%d\n", mincost);
}