最小费用最大流模板
2016-06-19 21:28
363 查看
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #define inf 2147483647 using namespace std; struct data { int from,to,next,cup,flow,cost; data(){from=-1,to=-1,next=-1,cup=-1,flow=-1,cost=-1;} }e[200]; int vis[200],head[200],d[200],p[200],a[200]; int cnt,flow,cost; int n,m; void add(int u,int v,int w,int c) {e[cnt].from=u,e[cnt].to=v,e[cnt].next=head[u],head[u]=cnt,e[cnt].cup=w,e[cnt].flow=0,e[cnt].cost=c,cnt++;} bool spfa(int s,int t) { memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) d[i]=inf; queue<int>q; q.push(s); d[s]=0,vis[s]=1,p[s]=0,a[s]=inf; while(!q.empty()) { int now=q.front(); q.pop(); vis[now]=0; for(int i=head[now];i>=0;i=e[i].next) { if(e[i].cup>e[i].flow&&d[e[i].from]<inf&&d[e[i].to]>d[e[i].from]+e[i].cost) { d[e[i].to]=d[e[i].from]+e[i].cost; p[e[i].to]=i; a[e[i].to]=min(a[e[i].from],e[i].cup-e[i].flow); if(!vis[e[i].to]) { q.push(e[i].to); vis[e[i].to]=1; } } } } if(d[t]==inf) return false; flow+=a[t]; cost+=d[t]*a[t]; int now=t; while(now!=s) { e[p[now]].flow+=a[t]; e[p[now]^1].flow-=a[t]; now=e[p[now]].from; } return true; } int main() { memset(head,-1,sizeof(head)); scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) { int u,v,w,c; scanf("%d%d%d%d",&u,&v,&w,&c); add(u,v,w,c); add(v,u,0,-c); } int s,t; scanf("%d%d",&s,&t); while(spfa(s,t)); cout<<flow<<' '<<cost; }
View Code
相关文章推荐
- ASP.NET DataList嵌套实现评论效果
- ScrollView与GridView的冲突
- java学习,第一天
- 粗浅看 移动端的WebApp发展之H5的无限活力
- 数组Array的基本操作
- cojs QAQ的序列 解题报告
- css基础
- Sphinx-for-chines中文分词安装配置及API调用
- HTTP文件断点续传的原理
- 上拉下拉刷新数据
- 访问修饰符,命名空间
- 【leetCode】House Robber II python实现
- spring--bean 标签的一些属性的配置
- jdbc连接mysql数据库小例子(代码)
- 如何创建Windows服务
- PHP面向对象-特征之一:继承
- 面向对象的继承性
- Python+Selenium进行UI自动化测试项目中,常用的小技巧3:写入excel表(python,xlsxwriter)
- equals和"=="的区别
- 使用 Sphinx 更好地进行 MySQL 搜索