bool makeLevel(int** a, int s, int t, int* level, int n) { for(int i=0; i<n; i++) level[i]=-1; level[s]=0; queue<int> mq; mq.push(s); while(!mq.empty()) { int len=mq.size(); while(len--) { int curnode=mq.front(); mq.pop(); for(int i=0; i<n; i++) { if(level[i]==-1 && a[curnode][i]>0) { level[i]=level[curnode]+1; mq.push(i); } } } } return level[t]!=-1; } int findFlow(int** a, int x, int t, int n, int* level, int flow) { if(x==t) return flow; int ret=0; for(int i=0; i<n; i++) { if(level[i]==level[x]+1 && a[x][i]>0 && (ret=findFlow(a,i,t,n,level,min(flow,a[x][i])))) { a[i][x]+=ret; a[x][i]-=ret; return ret; } } return 0; } void Dinic(int** a, int s, int t, int n) { int* level=new int[n]; int flow=0; int maxflow=0xfffff; while(makeLevel(a,s,t,level,n)) { flow+=findFlow(a,s,t,n,level,maxflow); } cout << flow << endl; delete [] level; }
|