您的位置:首页 > 其它

MincostMaxflow

2015-06-18 21:47 381 查看
</pre><pre name="code" class="cpp">#include <bits/stdc++.h>
using namespace std;
const int INF = ~0U>>1;
int totalcost;
int totalflow;
int n,m;
struct Ed{
int from; int to; int cap; int cost;
};
vector<Ed>edge;
vector<int>G[1024];
void AddEdge(int a, int b, int c, int d){
edge.push_back((Ed){a, b, c, d});
edge.push_back((Ed){b, a, 0, -d});
int size;
size = edge.size();
G[a].push_back(size - 2);
G[b].push_back(size - 1);
}

bool spfa(int s, int t){
bool visit[1024];
int d[1024];
int a[1024];
int pred[1024];
int p;
queue<int>q;
memset(visit, 0, sizeof(visit));
memset(a, 0, sizeof(a));
memset(pred, 0, sizeof(pred));
for(int i = 1; i <= n; i++) d[i] = INF;
visit[s] = 0;
a[s] = INF;
visit[s] = 1;
d[s] = 0;
q.push(s);
while(!q.empty()){
p = q.front();
q.pop();
visit[p] = 0;
for(int i = 0; i < G[p].size(); i ++){
Ed &e = edge[G[p][i]];
if(e.cap > 0 && d[e.to] > d[p] + e.cost){
a[e.to] = min(a[p], e.cap);
d[e.to] = d[p] + e.cost;
pred[e.to] = G[p][i];
if(!visit[e.to]){q.push(e.to); visit[e.to] = 1;}
}
}
}
if(d[t] == INF) return 0;
totalflow += a[t];
totalcost += a[t] * d[t];
for(int i = t; i != s; i = edge[pred[i]].from){
edge[pred[i]].cap -= a[t];
edge[pred[i] ^ 1].cap += a[t];
}
return 1;
}

int MCMF(int s, int t){
while(spfa(s, t));
}
int main(){
int s, t;
int a, b, c, d;
scanf("%d%d%d%d", &n, &m, &s, &t);
for(int i = 1; i <= m; i ++){
scanf("%d%d%d%d", &a, &b, &c, &d);
AddEdge(a, b, c, d);
}
MCMF(s, t);
printf("%d %d\n", totalflow, totalcost);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: