poj1273&&nefu473Drainage DitchesHal Burch(最大流)

來源:互聯網
上載者:User

這題是標準的入門模板題,不過因為點是從0開始的,而這道題目是沒有0的,所以要不然就在prepare語句那裡寫成prepare(m+1,1,m),要不然就從0開始,把每個點減一

#include<stdio.h>#include<iostream>using namespace std;const int oo=1e9;/**oo 表示無窮大*/const  int mm=111111111;/**mm 表示邊的最大數量,記住要是原圖的兩倍,在加邊的時候都是雙向的*/const  int mn=999;/**mn 表示點的最大數量*/int node,src,dest,edge;/**node 表示節點數,src 表示源點,dest 表示匯點,edge 統計邊數*/int ver[mm],flow[mm],next[mm];/**ver 邊指向的節點,flow 邊的容量 ,next 鏈表的下一條邊*/int head[mn],work[mn],dis[mn],q[mn];void prepare(int _node, int _src,int _dest){    node=_node,src=_src,dest=_dest;    for(int i=0; i<node; ++i)head[i]=-1;    edge=0;}/**增加一條 u 到 v 容量為 c 的邊*/void addedge( int u,  int v,  int c){    ver[edge]=v,flow[edge]=c,next[edge]=head[u],head[u]=edge++;    ver[edge]=u,flow[edge]=0,next[edge]=head[v],head[v]=edge++;}/**廣搜計算出每個點與源點的最短距離,如果不能到達匯點說明演算法結束*/bool Dinic_bfs(){    int i,u,v,l,r=0;    for(i=0; i<node; ++i)dis[i]=-1;    dis[q[r++]=src]=0;    for(l=0; l<r; ++l)        for(i=head[u=q[l]]; i>=0; i=next[i])            if(flow[i]&&dis[v=ver[i]]<0)            {                /**這條邊必須有剩餘容量*/                dis[q[r++]=v]=dis[u]+1;                if(v==dest)  return 1;            }    return 0;}/**尋找可行流的增廣路演算法,按節點的距離來找,加快速度*/int Dinic_dfs(  int u, int exp){    if(u==dest)  return exp;    /**work 是臨時鏈表頭,這裡用 i 引用它,這樣尋找過的邊不再尋找*/    for(  int &i=work[u],v,tmp; i>=0; i=next[i])        if(flow[i]&&dis[v=ver[i]]==dis[u]+1&&(tmp=Dinic_dfs(v,min(exp,flow[i])))>0)        {            flow[i]-=tmp;            flow[i^1]+=tmp;            /**正反向邊容量改變*/            return tmp;        }    return 0;}int Dicnic_flow(){    int i,ret=0,delta;    while(Dinic_bfs())    {        for(i=0; i<node; ++i)work[i]=head[i];        while(delta=Dinic_dfs(src,oo))ret+=delta;    }    return ret;}int main(){    int n,m,u,v,w;    ios::sync_with_stdio(false);    while(cin>>n>>m)    {        prepare(m,0,m-1);        for(int i=1; i<=n; i++)        {            cin>>u>>v>>w;            addedge(u-1,v-1,w);        }        int sum=Dicnic_flow();        cout<<sum<<endl;    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.