标签:use ace ++ return tree dinic ret min []
没事干写一发模板。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> #include<map> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<‘0‘||c>‘9‘) {if (c==‘-‘) f=-1;c=getchar();} while (c>=‘0‘&&c<=‘9‘) x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 510 #define M 1600 #define inf 1000000000 int n,m,p[N],v[N],u[N],tot=0,t=-1; bool flag[N]; int d[N],cur[N],q[N]; struct data{int to,nxt,cap,flow; }edge[M<<1]; map<int,bool> f; namespace tree { int p[N],fa[N],deep[N],len[N],t=0; struct data{int to,nxt,len;}edge[M<<1]; void addedge(int x,int y,int z){t++;edge[t].to=y,edge[t].nxt=p[x],edge[t].len=z,p[x]=t;} void dfs(int k) { for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=fa[k]) { deep[edge[i].to]=deep[k]+1; fa[edge[i].to]=k; len[edge[i].to]=edge[i].len; dfs(edge[i].to); } } void solve(int q) { while (q--) { int x=read(),y=read(),ans=100000000; if (deep[x]<deep[y]) swap(x,y); while (deep[x]>deep[y]) ans=min(ans,len[x]),x=fa[x]; while (x!=y) ans=min(ans,len[x]),ans=min(ans,len[y]),x=fa[x],y=fa[y]; printf("%d\n",ans); } } } void addedge(int x,int y,int z) { t++;edge[t].to=y,edge[t].nxt=p[x],edge[t].cap=z,edge[t].flow=0,p[x]=t; } bool bfs(int S,int T) { memset(d,255,sizeof(d));d[S]=0; int head=0,tail=1;q[1]=S; do { int x=q[++head]; for (int i=p[x];~i;i=edge[i].nxt) if (d[edge[i].to]==-1&&edge[i].flow<edge[i].cap) { d[edge[i].to]=d[x]+1; q[++tail]=edge[i].to; } }while (head<tail); return ~d[T]; } int work(int k,int T,int f) { if (k==T) return f; int used=0; for (int i=cur[k];~i;i=edge[i].nxt) if (d[k]+1==d[edge[i].to]) { int w=work(edge[i].to,T,min(f-used,edge[i].cap-edge[i].flow)); edge[i].flow+=w,edge[i^1].flow-=w; if (edge[i].flow<edge[i].cap) cur[k]=i; used+=w;if (used==f) return f; } if (used==0) d[k]=-1; return used; } void dinic(int S,int T) { for (int i=0;i<=t;i++) edge[i].flow=0; int ans=0; while (bfs(S,T)) { memcpy(cur,p,sizeof(p)); ans+=work(S,T,inf); } tree::addedge(S,T,ans); } void dfs(int k) { flag[k]=1; for (int i=p[k];~i;i=edge[i].nxt) if (!flag[edge[i].to]&&edge[i].flow<edge[i].cap) dfs(edge[i].to); } void solve(int l,int r) { if (l>=r) return; dinic(v[l],v[r]); memset(flag,0,sizeof(flag)); dfs(v[l]); int cnt=l-1; for (int i=l;i<=r;i++) if (flag[v[i]]) u[++cnt]=v[i]; cnt=r+1; for (int i=l;i<=r;i++) if (!flag[v[i]]) u[--cnt]=v[i]; for (int i=l;i<=r;i++) v[i]=u[i]; solve(l,cnt-1); solve(cnt,r); } int main() { #ifndef ONLINE_JUDGE freopen("mincuttree.in","r",stdin); freopen("mincuttree.out","w",stdout); const char LL[]="%I64d\n"; #else const char LL[]="%lld\n"; #endif n=read(),m=read(); memset(p,255,sizeof(p)); for (int i=1;i<=m;i++) { int x=read(),y=read(),z=read(); addedge(x,y,z),addedge(y,x,z); } for (int i=1;i<=n;i++) v[i]=i; solve(1,n); tree::dfs(1); int q=read(); tree::solve(q); return 0; }
标签:use ace ++ return tree dinic ret min []
原文地址:https://www.cnblogs.com/Gloid/p/9743341.html