网络流模板(Dinic)

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<cstdlib>
 7 #include<vector>
 8 using namespace std;
 9 typedef long long ll;
10 typedef long double ld;
11 typedef pair<int,int> pr;
12 const double pi=acos(-1);
13 #define rep(i,a,n) for(int i=a;i<=n;i++)
14 #define per(i,n,a) for(int i=n;i>=a;i--)
15 #define Rep(i,u) for(int i=head[u];i;i=Next[i])
16 #define clr(a) memset(a,0,sizeof(a))
17 #define pb push_back
18 #define mp make_pair
19 #define fi first
20 #define sc second
21 #define pq priority_queue
22 #define pqb priority_queue <int, vector<int>, less<int> >
23 #define pqs priority_queue <int, vector<int>, greater<int> >
24 #define vec vector
25 ld eps=1e-9;
26 ll pp=1000000007;
27 ll mo(ll a,ll pp){if(a>=0 && a<pp)return a;a%=pp;if(a<0)a+=pp;return a;}
28 ll powmod(ll a,ll b,ll pp){ll ans=1;for(;b;b>>=1,a=mo(a*a,pp))if(b&1)ans=mo(ans*a,pp);return ans;}
29 void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
30 //void add(int x,int y,int z){ v[++e]=y; next[e]=head[x]; head[x]=e; cost[e]=z; }
31 int dx[5]={0,-1,1,0,0},dy[5]={0,0,0,-1,1};
32 ll read(){ ll ans=0; char last=' ',ch=getchar();
33 while(ch<'0' || ch>'9')last=ch,ch=getchar();
34 while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
35 if(last=='-')ans=-ans; return ans;
36 }
37 #define M 1000
38 #define N 1000
39 const int INF=1<<30;
40 int head[N],level[N],q[N],e,n,m;
41 struct E_node{
42     int v,f,Next;
43 }edge[M];
44 void add(int x,int y,int z){
45     edge[++e].v=y; edge[e].f=z; edge[e].Next=head[x]; head[x]=e;
46     edge[++e].v=x; edge[e].f=0; edge[e].Next=head[y]; head[y]=e;
47 }
48 int bfs(int s,int t){
49     memset(level,0,sizeof(level));
50     level[s]=1;
51     int h=0,t_=1; q[h]=s;
52     while (h<t_){
53         int x=q[h++];
54         if (x==t) return 1;
55         for (int i=head[x];i;i=edge[i].Next){
56             int v=edge[i].v,f=edge[i].f;
57             if (!level[v] && f>0){
58                 level[v]=level[x]+1;
59                 q[t_++]=v;
60             }
61         }
62     }
63     return 0;
64 }
65 int dfs(int u,int maxf,int t){
66     if (u==t) return maxf;
67     int ret=0;
68     for (int i=head[u];i;i=edge[i].Next){
69         int v=edge[i].v,f=edge[i].f;
70         if (level[v]==level[u]+1 && f>0){
71             int Min=min(maxf-ret,f);
72             f=dfs(v,Min,t);
73             edge[i].f-=f;
74             edge[i^1].f+=f;
75             ret+=f;
76             if (ret==maxf) return ret;
77         }
78     }
79     return ret; 
80 }
81 int Dinic(int s,int t){
82     int ans=0;
83     while (bfs(s,t)) ans+=dfs(s,INF,t);
84     return ans;
85 }
86 int main(){
87     n=read(),m=read();
88     for (int i=1;i<=n;i++){
89         int x=read(),y=read(),c=read();
90         add(x,y,c);
91     }
92     printf("%d\n",Dinic(1,m));
93     return 0;
94 } 

 

posted @ 2017-07-19 22:06  SXia  阅读(234)  评论(0编辑  收藏  举报