最大流(Dinic模板)

http://acm.hdu.edu.cn/showproblem.php?pid=1532

 

 1 #include<cstdio>

 2  #include<cstring>

 3  #include<queue>

 4  #include<cmath>

 5  using namespace std;

 6  const int Ni = 210;

 7  const int MAX = 1<<26;

 8  struct Edge{

 9      int u,v,c;

10      int next;

11  }edge[20*Ni];

12  int n,m;

13  int edn;//边数

14  int p[Ni];//父亲

15  int d[Ni];

16  int sp,tp;//原点,汇点

17 

18  void addedge(int u,int v,int c)

19  {

20      edge[edn].u=u; edge[edn].v=v; edge[edn].c=c;

21      edge[edn].next=p[u]; p[u]=edn++;

22 

23      edge[edn].u=v; edge[edn].v=u; edge[edn].c=0;

24      edge[edn].next=p[v]; p[v]=edn++;

25  }

26  int bfs()

27  {

28      queue <int> q;

29      memset(d,-1,sizeof(d));

30      d[sp]=0;

31      q.push(sp);

32      while(!q.empty())

33      {

34          int cur=q.front();

35          q.pop();

36          for(int i=p[cur];i!=-1;i=edge[i].next)

37          {

38              int u=edge[i].v;

39              if(d[u]==-1 && edge[i].c>0)

40              {

41                  d[u]=d[cur]+1;

42                  q.push(u);

43              }

44          }

45      }

46      return d[tp] != -1;

47  }

48  int dfs(int a,int b)

49  {

50      int r=0;

51      if(a==tp)return b;

52      for(int i=p[a];i!=-1 && r<b;i=edge[i].next)

53      {

54          int u=edge[i].v;

55          if(edge[i].c>0 && d[u]==d[a]+1)

56          {

57              int x=min(edge[i].c,b-r);

58              x=dfs(u,x);

59              r+=x;

60              edge[i].c-=x;

61              edge[i^1].c+=x;

62          }

63      }

64      if(!r)d[a]=-2;

65      return r;

66  }

67 

68  int dinic(int sp,int tp)

69  {

70      int total=0,t;

71      while(bfs())

72      {

73          while(t=dfs(sp,MAX))

74          total+=t;

75      }

76      return total;

77  }

78  int main()

79  {

80      int i,u,v,c;

81      while(~scanf("%d%d",&m,&n))

82      {

83          edn=0;//初始化

84          memset(p,-1,sizeof(p));

85          sp=1;tp=n;

86          for(i=0;i<m;i++)

87          {

88              scanf("%d%d%d",&u,&v,&c);

89              addedge(u,v,c);

90          }

91          printf("%d\n",dinic(sp,tp));

92      }

93      return 0;

94  }

 

 

你可能感兴趣的:(dinic)