[poj1273]Drainage Ditches(最大流)
解题关键:最大流裸题
#include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> #include<cmath> #include<iostream> #include<queue> #include<vector> #define inf 0x3f3f3f3f #define MAX_V 252 using namespace std; typedef long long ll; struct edge{int to,cap,rev;};//终点,容量,反向边 vector<edge>G[MAX_V]; int level[MAX_V],iter[MAX_V]; int n,m,s,t; void add_edge(int from,int to,int cap){ G[from].push_back((edge){to,cap,(int)G[to].size()}); G[to].push_back((edge){from,0,(int)G[from].size()-1}); } void bfs(int s){ memset(level,-1,sizeof level); queue<int>que; level[s]=0; que.push(s); while(!que.empty()){ int v=que.front();que.pop(); for(int i=0;i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[e.to]<0){ level[e.to]=level[v]+1; que.push(e.to); } } } } int dfs(int v,int t,int f){ if(v==t) return f; for(int &i=iter[v];i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[v]<level[e.to]){ int d=dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap-=d; G[e.to][e.rev].cap+=d; return d; } } } return 0; } int dicnic(int s,int t){ int flow=0,f; while(1){ bfs(s); if(level[t]<0) return flow; memset(iter,0,sizeof iter); while((f=dfs(s,t,inf))>0){ flow+=f; } } return flow; } int main(){ int u,v,f; while(scanf("%d%d",&m,&n)!=EOF){ memset(G,0,sizeof G); for(int i=0;i<m;i++){ scanf("%d%d%d",&u,&v,&f); add_edge(u,v,f); } s=1,t=n; int ans=dicnic(s,t); printf("%d\n",ans); } return 0; }