最大流dinic模板
2015-07-28 01:13
176 查看
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <vector> #include <algorithm> #include <queue> #include <set> using namespace std; const int INF=0x3f3f3f3f; const int MAXN=2000; const int MAXM=10005; int n,m,u,v,w; struct Edge { int to,next,flow; }edge[MAXM]; int head[MAXN],tot; void add(int u,int v,int w) { edge[tot].to=v; edge[tot].flow=w; edge[tot].next=head[u]; head[u]=tot++; edge[tot].to=u; edge[tot].flow=0; edge[tot].next=head[v]; head[v]=tot++; } int dep[MAXN]; bool bfs(int s,int t) { int u; memset(dep,-1,sizeof(dep)); queue <int> q; q.push(s); dep[s]=0; while(!q.empty()) { u=q.front(); q.pop(); for(int i=head[u];~i;i=edge[i].next) { int v=edge[i].to; if(dep[v]==-1&&edge[i].flow>0) { dep[v]=dep[u]+1; if(v==t)return true; q.push(v); } } } return false; } int dfs(int s,int t,int x) { if(s==t)return x;int ans=x; for(int i=head[s];~i;i=edge[i].next) { int v=edge[i].to; if(dep[v]==dep[s]+1&&edge[i].flow>0) { int minn=dfs(v,t,min(x,edge[i].flow)); edge[i].flow-=minn; edge[i^1].flow+=minn; x-=minn; } } return ans-x; } int dinic() { int ans=0; while(bfs(1,n))ans+=dfs(1,n,INF); return ans; } int main() { //freopen("in.txt","r",stdin); int cas=1,T;scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m);tot=0; memset(head,-1,sizeof(head)); for(int i=0;i<m;++i) { scanf("%d%d%d",&u,&v,&w); add(u,v,w); } printf("Case %d: %d\n",cas++,dinic()); } return 0; }
相关文章推荐
- Leetcode Q6:ZigZag Conversion
- 深入掌握JMS(八):JMSReplyTo
- apache自带压力测试
- android Github-Client(ANDROID)开源之旅(三) ------ 巧用ViewPagerIndicator
- ubuntu笔记
- AutoCAD2013中曲线的绘制方法
- AutoCAD2013中曲线的绘制方法
- 指针变量复习
- BootStrap导航条
- 马的遍历问题
- Android应用闪屏的制作,手把手教
- 马的遍历问题
- php面试题1
- 读书笔记MoreEffectiveC++(18)
- ORM思想解析
- C# 接口《通俗解释》
- 最基本的无限极分类
- VS2010通过OLE操作Excel2010
- leetcode笔记:Merge Sorted Array
- dds的cube加载到opengl里后的处理方式。