题解
根据需求大概建立以下模型:
- 跑过路程最短
- 每条路只能走一次
- 出了第一个点和最后一个点,其他点都只能走一次
- 从第一个点走到最后一个点,最多可以走多少次
这好像是:
- 最短路
- 网络流流容量为1的边
- 拆点
- 最小割,也就是最大流
这不就是费用流嘛~板子套一下就好了
有不能理解拆点的吗?
可以看看我另外一篇博客 P2766 最长不下降子序列问题 · LIS + 网络流 + 拆点
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int n, m, k;
namespace cost_flows { //最小费用最大流板子
//设定起点和终点
int st;//起点-源点
int ed;//终点-汇点
struct egde {
int to, next;
int flow;//剩余流量
int dis; //花费
} e[N * 2];
int head[N], tot = 1;
void add(int u, int v, int w, int cost) {//出发点 下一个点 流量 费用
e[++tot] = {v, head[u], w, cost};
head[u] = tot;
e[++tot] = {u, head[v], 0, -cost};
head[v] = tot;//费用流反相边流量为0 费用是-dis
}
queue<int> q;
int flow[N];//增广路上最小流量
int inq[N];//是否在队里里 等同于vis
int last[N];//每个点所连的前一条边的编号
int dis[N];//到达每个节点的最小花费 即 最短路
int pre[N];//每个节点的前驱节点
bool spfa() {
memset(flow, INF, sizeof(flow));
memset(dis, INF, sizeof(dis));//注意了 这里是最大值
memset(inq, 0, sizeof(inq));
q.push(st);
dis[st] = 0;
inq[st] = 1;//在队列中 标记
pre[ed] = -1;//ok 还没有到达汇点
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = 0;//出队 标记
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].to;
if (dis[v] > dis[u] + e[i].dis && e[i].flow) { //有流量才能松弛
dis[v] = dis[u] + e[i].dis;
pre[v] = u;
last[v] = i;
flow[v] = min(flow[u], e[i].flow);
if (!inq[v]) {
inq[v] = 1;
q.push(v);
}
}
}
}
return pre[ed] != -1;//即 没有到达汇点
}
int max_flow, min_cost;
void MCMF() {// - 费用流主体
while (spfa()) {//如果有增广路
int now = ed;
max_flow += flow[ed];
min_cost += flow[ed] * dis[ed];
while (now != st) {//遍历这条增广路
//从汇点一直回溯到源点
e[last[now]].flow -= flow[ed];
e[last[now] ^ 1].flow += flow[ed];
now = pre[now];
}
}
}
void init() {
tot = 1;
memset(head, 0, sizeof(head));
while (!q.empty()) q.pop();
max_flow=0;
min_cost=0;
}
}
using namespace cost_flows;
int main() {
ios::sync_with_stdio(0);
cin>>n>>m;
st=0,ed=2*n+1;
//拆点
for (int i = 1; i <= n; ++i) {
if(i==1||i==n) add(i,i+n,INF,0);
else add(i,i+n,1,0);
}
for (int i = 1,a,b,c; i <= m; ++i) {
cin>>a>>b>>c;
add(a+n,b,1,c);
}
add(st,1,INF,0);
add(n+n,ed,INF,0);
MCMF();
printf("%d %d\n", max_flow,min_cost);
return 0;
}