标签:
Description
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
裸的 dinic 代码如下... 可做模板 orzzzz
#include<iostream> #include<cstring> #include<cstdio> #include<deque> #include<queue> #include<stack> #include<map> #include<algorithm> #include<vector> #define INFINFE 999999999 #define N 300 using namespace std; int G[300][300]; bool visited[300]; int layer[300]; int n,m; bool countlayer() { // cout<<"***"<<endl; //int Layer=0; deque<int>q; memset(layer,0xff,sizeof(layer)); layer[1]=0; q.push_back(1); while(!q.empty()) { int v=q.front(); q.pop_front(); for(int j=1; j<=m; j++) { if(G[v][j]>0&&layer[j]==-1) { layer[j]=layer[v]+1; if(j==m) return true; else q.push_back(j); } } } return false; } int Dinic() { int i; //int s; int nmaxflow=0; deque<int>q; while(countlayer()) { while(!q.empty()) q.pop_back(); q.push_back(1); memset(visited,0,sizeof(visited)); visited[1]=1; while(!q.empty()) { int nd=q.back(); if(nd==m) { int nminc=INFINFE; int nminc_vs; for(unsigned int i=1; i<q.size(); i++) { int vs=q[i-1]; int ve=q[i]; if(G[vs][ve]>0) { if(nminc>G[vs][ve]) { nminc=G[vs][ve]; nminc_vs=vs; } } } nmaxflow+=nminc; for(unsigned int i=1; i<q.size(); i++) { int vs=q[i-1]; int ve=q[i]; G[vs][ve]-=nminc; G[ve][vs]+=nminc; } while(!q.empty()&&q.back()!=nminc_vs) { visited[q.back()]=0; q.pop_back(); } } else { for(i=1; i<=m; i++) { if(G[nd][i]>0&&layer[i]==layer[nd]+1&&!visited[i]) { visited[i]=1; q.push_back(i); break; } } if(i>m) q.pop_back(); } } } return nmaxflow; } int main() { while(cin>>n>>m) { int i; int s,e,c; memset(G,0,sizeof(G)); for(i=0; i<n; i++) { cin>>s>>e>>c; G[s][e]+=c; } cout<<Dinic()<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/hsd-/p/4685599.html