上下界费用流板子题,不赘述
感觉最重要的一个点 是题目要求回到一号点 我们这样的连边 恰好保证了要求
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int V = 20100;
const int E = 201000;
template<typename T>
struct MinCostGraph {
int s, t, vtot;
int h[V], idx;
T d[V], flow, cost;
int pre[V];
bool vis[V];
int f[E*2];
int w[E*2];
int e[E*2];
int ne[E*2];
/* struct edge {
int v, nxt;
T f, c;
} e[E * 2];
/*void addedge(int u,int v, T f, T c, T f2 = 0) {
e[etot]= {v, head[u], f, c};
head[u] = etot++;
e[etot]= {u, head[v], f2, -c};
head[v] = etot++;
}*/
void add(int a, int b, int c, int d) {
e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx ++ ;
e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx ++ ;
}
bool spfa() {
T inf = numeric_limits<T>::max() / 2;
for (int i = 1; i <= vtot; i++) {
d[i] = inf;
vis[i] = false;
pre[i] = -1;
}
d[s] = 0;
vis[s] = true;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for(int i=h[u]; ~i; i=ne[i]) {
int v = e[i];
if (f[i] && d[v] > d[u] + w[i]) {
d[v] = d[u] + w[i];
pre[v] = i;
if (!vis[v]) {
vis[v] = 1;
q.push(v);
}
}
}
}
return d[t] != inf;
}
void augment() {
int u = t;
T q = numeric_limits<T>::max();
while (~pre[u]) {
q = min(q, f[pre[u]]);
u = e[pre[u] ^ 1];
}
flow += q;
cost += q * d[t];
u = t;
while (~pre[u]) {
f[pre[u]] -= q;
f[pre[u] ^ 1] += q;
u = e[pre[u] ^ 1];
}
}
pair<T, T> solve() {
flow = 0;
cost = 0;
while (spfa()) augment();
return {flow, cost};
}
void init(int s_, int t_, int vtot_) {
s = s_;
t = t_;
vtot = vtot_;
idx = 0;
for (int i = 1; i <= vtot; i++) h[i] = -1;
}
};
const int N=1e5+10;
MinCostGraph<int> g;
int n, m;
int T,S,EE;
int sum;
int s,t;
int d[N];
int inf=1<<30;
int tot;
int main() {
cin>>T>>S>>EE;
while(T--) {
sum=0;
tot=0;
memset(d,0,sizeof(d));
cin>>n>>m;
s=n+1,t=n+2;
g.init(s,t,t);
for(int i=1; i<=m; i++) {
int a,b;
char ch;
cin>>a>>b>>ch;
if(ch=='A') {
g.add(a,b,inf-1,EE);
d[a]--,d[b]++;
sum+=EE;
} else if(ch=='B') {
d[a]--,d[b]++;
sum+=EE;
} else if(ch=='C') {
g.add(a,b,inf,EE);
} else g.add(a,b,1,EE);
}
/*for(int i=2;i<=n;i++){
g.add(i,1,inf,0);
}*/
for(int i=1; i<=n; i++) {
if(d[i]<0)g.add(i,t,-d[i],0);
else if(d[i]>0)g.add(s,i,d[i],0),tot=tot+d[i];
}
pair<int,int> ans=g.solve();
if(ans.first!=tot)cout<<-1<<endl;
else cout<<ans.second+sum<<endl;
}
}