最大流

来源:互联网 发布:sqlalchemy sql注入 编辑:程序博客网 时间:2024/06/05 16:33
  1. <span style="font-size:14px;">#define N 10000   
  2. int n,m,len,s,t;  
  3. struct node{  
  4.     int x,y,e,pre;  
  5. };  
  6. node a[N*2];  
  7. int pre[N],que[N],stage[N];  
  8.   
  9. void init()  
  10. {  
  11.     len=0s=0t=m+n+1;//s和t自己改的  
  12.     memset(pre,-1,sizeof(pre));  
  13. }  
  14. void addpage(int x,int y,int t)  
  15. {  
  16.     a[len].x=x;a[len].y=y;a[len].e=t;  
  17.     a[len].pre=pre[x];pre[x]=len++;  
  18. }  
  19. bool bfs()  
  20. {  
  21.     queue<int>q;  
  22.     memset(stage,-1,sizeof(stage));  
  23.     stage[s]=0; q.push(s);  
  24.     while(!q.empty())  
  25.     {  
  26.         int x=q.front(); q.pop();  
  27.         for(int i=pre[x]; i!=-1; i=a[i].pre)  
  28.             if(a[i].e>0 && stage[a[i].y]==-1)  
  29.             {  
  30.                 stage[a[i].y]=stage[a[i].x]+1;  
  31.                 q.push(a[i].y);  
  32.                 if(a[i].y==t) return true;  
  33.             }  
  34.     }  
  35.     return false;  
  36. }  
  37. int dfs()  
  38. {  
  39.     int sum=0;  
  40.     while(bfs())  
  41.     {  
  42.         int tail=0,u=s;  
  43.         while(true)  
  44.         {  
  45.             if(u==t)  
  46.             {  
  47.                 int Min=inf,mark;  
  48.                 rep(i,tail)  
  49.                     if(a[que[i]].e<Min)  
  50.                         mark=i,Min=a[que[i]].e;  
  51.                 rep(i,tail)  
  52.                     a[que[i]].e-=Min,a[que[i]^1].e+=Min;  
  53.                 sum+=Min,tail=mark,u=a[que[tail]].x;  
  54.             }  
  55.             int i;  
  56.             for( i=pre[u]; i!=-1; i=a[i].pre)  
  57.             {  
  58.                 int y=a[i].y;  
  59.                 if(stage[y]==-1) continue;  
  60.                 if(stage[y]==stage[u]+1 && a[i].e>0) break;  
  61.             }  
  62.             if(i!=-1)//回朔  
  63.                 que[tail++]=i,u=a[i].y;  
  64.             else  
  65.             {  
  66.                 if(tail==0) break;  
  67.                 stage[u]=-1;  
  68.                 u=a[que[--tail]].x;  
  69.             }  
  70.         }  
  71.     }  
  72.     return sum;  
  73. }  
  74. int main()  
  75. {   
  76.     init();  
  77.     //加正反边  
  78.     return dfs();  
  79.    return 0;  
  80. }</span>  
0 0
原创粉丝点击