题目链接 P6061 [加油武汉]疫情调查
这道题一上来,就让我看到了最小费用可行流的影子,每个点至少经过一次,且不限经过次数,那么不就是最小费用可行流了嘛。
于是,我们就开始建图,对于每个点拆点,然后设置下限为1,上限INF,记得一件事,要开long long,INF也要设置的足够的大,不然会WA。对于自己的自环,那么就可以是。
对于M条边也就是,这里是因为拆点了。
然后就是跑一个费用流,也没有遇到讨论区中说到的TLE的问题,但是讨论区怎么净是些我想不到的做法QAQ!
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e3 + 7, maxM = 2e4 + 7;
int N, M, head[maxN], cnt, In_det_Out[maxN];
struct Eddge
{
int nex, u, v; ll flow, cost;
Eddge(int a=-1, int b=0, int c=0, ll d=0, ll f=0):nex(a), u(b), v(c), flow(d), cost(f) {}
} edge[maxM];
inline void addEddge(int u, int v, ll flow, ll cost)
{
edge[cnt] = Eddge(head[u], u, v, flow, cost);
head[u] = cnt++;
}
inline void _add(int u, int v, ll flow, ll cost) { addEddge(u, v, flow, cost); addEddge(v, u, 0, -cost); }
struct MaxFlow_MinCost
{
int pre[maxN], S, T; ll Flow[maxN], dist[maxN];
queue<int> Q;
bool inque[maxN];
inline bool spfa()
{
for(int i=0; i<=T; i++) { pre[i] = -1; dist[i] = INF; inque[i] = false; }
while(!Q.empty()) Q.pop();
Q.push(S); dist[S] = 0; inque[S] = true; Flow[S] = INF;
while(!Q.empty())
{
int u = Q.front(); Q.pop(); inque[u] = false;
ll f, w;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].v; f = edge[i].flow; w = edge[i].cost;
if(f && dist[v] > dist[u] + w)
{
dist[v] = dist[u] + w;
Flow[v] = min(Flow[u], f);
pre[v] = i;
if(!inque[v])
{
inque[v] = true;
Q.push(v);
}
}
}
}
return ~pre[T];
}
inline ll EK()
{
ll sum_Cost = 0;
while(spfa())
{
int now = T, las = pre[now];
while(now ^ S)
{
edge[las].flow -= Flow[T];
edge[las ^ 1].flow += Flow[T];
now = edge[las].u;
las = pre[now];
}
sum_Cost += dist[T] * Flow[T];
}
return sum_Cost;
}
} MF;
inline void init()
{
cnt = 0; MF.S = 0; MF.T = (N << 1) + 1;
for(int i=0; i<=MF.T; i++) { head[i] = -1; In_det_Out[i] = 0; }
}
int main()
{
scanf("%d%d", &N, &M);
init();
for(int i=1; i<=N; i++)
{
In_det_Out[i] --; In_det_Out[N + i] ++;
_add(i, i + N, INF, 0);
}
for(int i=1, wi; i<=N; i++)
{
scanf("%d", &wi);
_add(i + N, i, INF, wi);
}
for(int i=1, u, v, w; i<=M; i++)
{
scanf("%d%d%d", &u, &v, &w);
_add(N + u, v, INF, w);
}
for(int i=1; i<MF.T; i++)
{
if(In_det_Out[i] > 0)
{
_add(MF.S, i, In_det_Out[i], 0);
}
else
{
_add(i, MF.T, -In_det_Out[i], 0);
}
}
printf("%lld\n", MF.EK());
return 0;
}