标签:道路 最大流 pop flow ges 一个 == lse ack
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
using namespace std;
const int N=210;
const int INF=0X3F3F3F3F;
int n,m,e;
int no[N];
int overload;//需要清扫的道路数目
int sum;//根据需要清扫的道路数目可知必须要消耗的包子数目,注意这里仅仅是需要清扫的道路的必须的包子数目,而不是全部的
struct Edge {
int from, to, cap, flow, cost;
};
struct MCMF {
int n, m;
vector<Edge> edges;
vector<int> G[N];
int d[N], inq[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 AddEdge(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});
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) {
//M(inq, 0); M(d, INF);
memset(inq,0,sizeof(inq));
memset(d,INF,sizeof(d));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> q;
q.push(s);
while (!q.empty()) {
int x = q.front(); q.pop();
inq[x] = 0;
for (int i = 0; i < G[x].size(); ++i) {
Edge &e = edges[G[x][i]];
if (d[e.to] > d[x] + e.cost && e.cap > e.flow) {
d[e.to] = d[x] + e.cost;
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap-e.flow);
if (inq[e.to]) continue;
q.push(e.to); inq[e.to] = 1;
}
}
}
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 Mincost(int s, int t) {
int flow = 0, cost = 0;
while (spfa(s, t, flow, cost));
if(flow!=overload)
return -1;
return cost;
}
}solver;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t,s;
cin>>t>>s>>e;
while(t--){
overload=0;
sum=0;
int st,ed;
cin>>n>>m;
st=0,ed=n+1;
memset(no,0,sizeof(no));
solver.init(n+1);
for(int i=0;i<m;i++){
int x,y;
char c;
cin>>x>>y>>c;
if(c=='A'){//需要被清理,可以走无数遍,上限为无穷,下限为1
solver.AddEdge(x,y,INF,e);
no[x]--;
no[y]++;
sum+=e;
}else if(c=='B'){//需要被清理,只能走一遍,上限为1,下限也为1
no[x]--;
no[y]++;
sum+=e;
}else if(c=='C'){//不要被清理,可以走无数遍,上限为无穷,下限为0
solver.AddEdge(x,y,INF,e);
}else{//不需要被清理,但是只能走一遍,上限为1,下限为0
solver.AddEdge(x,y,1,e);
}
}
for(int i=1;i<=n;i++){//因为这里的下限刚好是1,所以可以采用++,--的方法来统计一个顶点共有多少次上限-下限
if(no[i]>0){//后结点
solver.AddEdge(st,i,no[i],0);//一下两条路属于附加结点,附加边,所以费用是0
overload+=no[i];
}else if(no[i]<0){//前结点
solver.AddEdge(i,ed,-no[i],0);
}
}
cout<<solver.Mincost(st,ed)+sum<<endl;
}
//system("pause");
return 0;
}
标签:道路 最大流 pop flow ges 一个 == lse ack
原文地址:https://www.cnblogs.com/GarrettWale/p/11441918.html