poj 2135 最小费用最大流模板题目;
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<cctype>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<string>
#define ll long long
#define MAX 1010
#define eps 1e-8
#define INF INT_MAX
using namespace std;
struct Edge{
int from, to,cap,flow,cost;
};
vector<int>G[MAX];
vector<Edge>edges;
int n;
void init(){
for (int i=0; i<MAX; 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});
int k = edges.size();
G[from].push_back(k-2);
G[to].push_back(k-1);
}
int d[MAX],inq[MAX],p[MAX],a[MAX];
bool Bellman_ford(int s, int t, int& flow, int& cost){
for (int i=0; i<n; i++) d[i] = (i == s ? 0 : INF);
memset(inq,0,sizeof(inq));
queue<int>q;
inq[s] = 1;
p[s] = 0;
a[s] = INF;
q.push(s);
while (!q.empty()){
int u = q.front();
q.pop();
inq[u] = 0;
for (int i=0; i<G[u].size(); i++){
Edge& e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] > d[u] + e.cost){
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u],e.cap - e.flow);
if (!inq[e.to]){
q.push(e.to);
inq[e.to] = 1;
}
}
}
}
if (d[t] == INF) return false;
flow += a[t];
cost += a[t]*d[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 (Bellman_ford(s,t,flow,cost));
return cost;
}
int main(){
int m;
while (scanf("%d%d",&n,&m) != EOF){
int x,y,z;
init();
for (int i=0; i<m; i++){
scanf("%d%d%d",&x,&y,&z);
addEdge(x,y,1,z);
addEdge(y,x,1,z);
}
addEdge(0,1,2,0);
addEdge(n,n+1,2,0);
n += 2;
printf("%d\n",Mincost(0,n-1));
}
return 0;
}
1843

被折叠的 条评论
为什么被折叠?



