洛谷P3386
網(wǎng)絡(luò)流解二分圖;
dinic 詳解
詳解
上代碼
#include<cstdio> #include<queue> #include<cstring> using namespace std;const int N = 2005; const int M = 1002005; const int INF = 0x7fffffff; struct Edge {int v,val,nxt,rev; }; Edge e[M<<1]; int fe[N]; queue<int> q; int dep[N]; int n,m,s,t;bool bfs() {while(!q.empty()) q.pop();memset(dep,0,sizeof(dep));q.push(s); dep[s] = 1;while(!q.empty()){int c = q.front(); q.pop();for(int i=fe[c]; i; i=e[i].nxt){if(e[i].val>0 && !dep[e[i].v]){dep[e[i].v] = dep[c]+1;q.push(e[i].v); }}}if(dep[t]) return true;else return false; }int dfs(int pos,int cur) {if(pos==t) return cur;int rst = cur;for(int i=fe[pos]; i; i=e[i].nxt){if(dep[e[i].v]==dep[pos]+1 && e[i].val>0 && rst){int flow = dfs(e[i].v,min(e[i].val,rst));if(flow>0){e[i].val -= flow;rst -= flow;e[e[i].rev].val += flow;}}}return cur-rst; }int dinic() {int ans = 0;while(bfs()) ans += dfs(s,INF);return ans; }void addedge(int u,int v,int val,int rev) {e[++m].v = v; e[m].val = val; e[m].rev = rev;e[m].nxt = fe[u]; fe[u] = m; }int main() {int n1,n2,m0; m = 0;scanf("%d%d%d",&n1,&n2,&m0);n = n1+n2+2;for(int i=1; i<=m0; i++){int x,y;scanf("%d%d",&x,&y);if(x<=n1 && y<=n2){addedge(x+1,y+n1+1,1,m+2);addedge(y+n1+1,x+1,0,m);}}for(int i=1; i<=n1; i++){addedge(1,i+1,1,m+2);addedge(i+1,1,0,m);}for(int i=1; i<=n2; i++){addedge(i+n1+1,n,1,m+2);addedge(n,i+n1+1,0,m);}s = 1; t = n;printf("%d\n",dinic()); return 0; }總結(jié)
- 上一篇: navicat新建数据库
- 下一篇: 史上最强Tomcat8性能优化