首页 > 代码库 > poj1273:Drainage Ditches

poj1273:Drainage Ditches

最大流模板题~

技术分享
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<string.h>
 4 #define INF 100000000
 5 using namespace std;
 6 
 7 const int MAXN=10005;
 8 struct node
 9 {
10     int v,f;
11     node *next,*rev;       
12 }pool[MAXN],*h[MAXN];
13 int cnt,S,T;
14 int que[MAXN],level[MAXN],st,ed;
15 void addedge(int u,int v,int len)
16 {
17     node *p=&pool[++cnt],*q=&pool[++cnt];
18     p->v=v;p->next=h[u];h[u]=p;p->f=len;p->rev=q;
19     q->v=u;q->next=h[v];h[v]=q;q->f=0;q->rev=p;   
20 }
21 bool make_level()
22 {
23     int u,v;
24     st=ed=0;
25     for(int i=1;i<=T;i++) level[i]=-1;
26     que[ed++]=S;level[S]=1;
27     while(st<ed)
28     {
29         u=que[st++];
30         for(node *p=h[u];p;p=p->next)
31             if(p->f && level[v=p->v]==-1)
32             {
33                 level[v]=level[u]+1;
34                 que[ed++]=v;
35                 if(level[T]!=-1) return true; 
36             }
37     }
38     return false;
39 }
40 int find(int u,int k)
41 {
42     if(u==T) return k;
43     int s=0,t,v;
44     for(node *p=h[u];p;p=p->next)
45         if(s<k && level[v=p->v]==level[u]+1 && p->f)
46         {
47             t=find(v,min(k-s,p->f));
48             if(t)
49             {
50                 s+=t;
51                 p->f-=t;
52                 p->rev->f+=t;     
53             }
54         }
55     if(s==0) level[u]=-1;
56     return s;
57 }
58 int dinic()
59 {
60     int ret=0;
61     while(make_level()) ret+=find(S,INF);
62     return ret;    
63 }
64 
65 int main()
66 {
67     int m,n,i,a,b,c;
68     while(scanf("%d%d",&n,&m)!=EOF)
69     {
70         S=1;T=m;
71         memset(h,NULL,sizeof(h));
72         memset(pool,0,sizeof(pool));cnt=0;
73         for(i=0;i<n;i++) scanf("%d%d%d",&a,&b,&c),addedge(a,b,c);
74         printf("%d\n",dinic());              
75     }
76     return 0;    
77 }
View Code

 

poj1273:Drainage Ditches