bzoj3894 文理分科
题目描述:
题解:
最小割。
对于不考虑组合的情况,可以:
- $S->x$,边权为$art_x$;
- $x->T$,边权为$science_x$;
这样跑出来的总权值-最小割等于正解贪心。
考虑加上组合,那么可以:
- 新建点$y$代表文科组合,$z$代表理科组合;
- $S->y$,边权$sameart_x$;
- $y->x$,$y->xx$($xx$为$x$相邻点),边权$inf$;
- $z$同理。
代码:
#include<queue> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const int N = 30050; const int inf = 0x3f3f3f3f; const ll Inf = 0x3f3f3f3f3f3f3f3fll; template<typename T> inline void read(T&x) { T f = 1,c = 0;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){c=c*10+ch-'0';ch=getchar();} x = f*c; } int n,m,tot,S,T,hed[N],cnt=1,nm[105][105]; int dx[5]={-1,1,0,0}; int dy[5]={0,0,-1,1}; bool check(int x,int y){return x>=1&&y>=1&&x<=n&&y<=m;} struct EG { int to,nxt; ll fl; }e[24*N]; void ae(int f,int t,ll fl) { e[++cnt].to = t; e[cnt].nxt = hed[f]; e[cnt].fl = fl; hed[f] = cnt; } void AE(int f,int t,ll fl) { ae(f,t,fl); ae(t,f,0); } int cur[N],dep[N]; bool vis[N]; bool bfs() { queue<int>q; memcpy(cur,hed,sizeof(cur)); memset(dep,0x3f,sizeof(dep)); dep[S] = 0,vis[S] = 1;q.push(S); while(!q.empty()) { int u = q.front(); q.pop(); for(int j=hed[u];j;j=e[j].nxt) { int to = e[j].to; if(e[j].fl&&dep[to]>dep[u]+1) { dep[to] = dep[u]+1; if(!vis[to])vis[to]=1,q.push(to); } } vis[u] = 0; } return dep[T]!=inf; } ll dfs(int u,ll lim) { if(u==T||!lim)return lim; ll fl = 0,f; for(int j=hed[u];j;j=e[j].nxt) { int to = e[j].to; if(dep[to]==dep[u]+1&&(f=dfs(to,min(lim,e[j].fl)))) { fl += f,lim -= f; e[j].fl -= f,e[j^1].fl += f; if(!lim)break; } } return fl; } ll dinic() { ll ret = 0; while(bfs())ret+=dfs(S,Inf); return ret; } int main() { read(n),read(m); ll ans = 0; S = ++tot,T = ++tot; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) nm[i][j] = ++tot; ll w; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { read(w);ans+=w; AE(S,nm[i][j],w); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { read(w);ans+=w; AE(nm[i][j],T,w); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { read(w);ans+=w; int u = nm[i][j] + n*m; AE(S,u,w); for(int k=0;k<=4;k++) { int x = i+dx[k],y = j+dy[k]; if(check(x,y))AE(u,nm[x][y],Inf); } } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { read(w);ans+=w; int u = nm[i][j] + 2*n*m; AE(u,T,w); for(int k=0;k<=4;k++) { int x = i+dx[k],y = j+dy[k]; if(check(x,y))AE(nm[x][y],u,Inf); } } printf("%lld\n",ans-dinic()); return 0; }