传送门:https://www.luogu.org/problemnew/show/P2153
每个点只能跑一次,所以我们把点拆开,中间连一条容量为1,费用为0的边,然后跑一下最小费用流就完事了。
代码在下面:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
const int maxn= 2020;
using namespace std;
struct edge
{
int to, cap, cost, rev;
};
vector<edge>G[maxn];
int dis[maxn];
int pv[maxn], pe[maxn];
int h[maxn];
void add_edge(int from, int to, int cap, int cost)
{
G[from].push_back({to, cap, cost, G[to].size()});
G[to].push_back({from, 0, -cost, G[from].size()-1});
}
void dijkstra(int s)
{
struct node
{
int now;
int cost;
bool operator < (const node &a) const
{
return cost > a.cost;
}
};
memset(dis,INF,sizeof(dis));
dis[s] = 0;
priority_queue<node>q;
q.push({s, dis[s]});
while (!q.empty()) {
int now = q.top().now;
int nowc = q.top().cost;
q.pop();
if(dis[now]<nowc) continue;
for (int i = 0; i < G[now].size(); ++i)
{
edge &e = G[now][i];
if (e.cap > 0 && dis[e.to] > dis[now] + e.cost + h[now]-h[e.to])
{
dis[e.to] = dis[now] + e.cost + h[now] - h[e.to];
pv[e.to] = now;
pe[e.to] = i;
q.push({e.to, dis[e.to]});
}
}
}
}
pair<int, int> min_cost_max_flow(int s, int t) {
int flow = 0;
int cost = 0;
while (true)
{
dijkstra(s);
if (dis[t] == INF) return {flow, cost};
for(int i=0;i<maxn;i++)
{
h[i] += dis[i];
}
int d = INF;
for (int v = t; v != s; v = pv[v])
{
d = min(d, G[pv[v]][pe[v]].cap);
}
flow += d;
cost += d*h[t];
for (int v = t; v != s; v = pv[v])
{
edge &e = G[pv[v]][pe[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
int n, m, s, t;
while (cin >> n >> m)
{
init();
s = 1;
t = 2*n;
for(int i=1;i<=n;i++)
{
add_edge(i,i+n,1,0);
}
add_edge(s,n+1,INF,0);
add_edge(n,t,INF,0);
for (int i = 0; i < m; ++i)
{
int x,y,z;
cin>>x>>y>>z;
add_edge(x+n,y,1,z);
}
pair<int, int>ans = min_cost_max_flow(s, t);
cout << ans.first << " " << ans.second << endl;
}
return 0;
}