1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include<iostream> #include<cstdio> #include<cstdlib> #include<memory.h> #include<algorithm> #include<queue> using namespace std; const int MAXN=2005; const int MAXM=2005; const int inf=2147483647; int n,m,x,y,z,sink,source,ans,depth[MAXN]; struct EDGE{ int next; int to; int weight; }; EDGE graph[MAXM]; int head[MAXN]={0},nume=-1;
void adde(int f,int t,int w){ graph[++nume].next=head[f]; graph[nume].to=t; graph[nume].weight=w; head[f]=nume; }
int bfs(){ memset(depth,0,sizeof(depth)); queue<int> q; int now; int i; while(!q.empty()) q.pop(); q.push(source); depth[source]=1; do{ now=q.front(); q.pop(); for(i=head[now];i!=-1;i=graph[i].next){ if(graph[i].weight!=0&&depth[graph[i].to]==0){ depth[graph[i].to]=depth[now]+1; q.push(graph[i].to); } } }while(!q.empty()); if(depth[sink]==0)return 0; return 1; }
int dfs(int i,int m){ int j,t; if(i==sink) return m; for(j=head[i];j!=-1;j=graph[j].next) if((depth[graph[j].to]==depth[i]+1) &&graph[j].weight!=0){ t=dfs(graph[j].to,min(m,graph[j].weight)); if(t>0){ graph[j].weight-=t; graph[j^1].weight+=t; return t; } } return 0; }
void dinic(){ int t; while(bfs()) while(t=dfs(source,inf)) ans+=t; }
int main(){ int i; while(scanf("%d%d",&m,&n)!=EOF){ memset(head,-1,sizeof(head)); nume=-1; for(i=1;i<=m;i++){ scanf("%d%d%d",&x,&y,&z); adde(x,y,z); adde(y,x,0); } source=1; sink=n; ans=0; dinic(); printf("%d\n",ans); } return 0; }
|