# 【BZOJ2127】happiness（网络流）

### 建图

1. $$1,2$$同选文：割去$$1->t,2->t$$，得$$sum-(b_1+\frac{d_{1,2}}2)-(b_2+\frac{d_{1,2}}2)=a_1+a_2+c_{1,2}$$
2. $$1,2$$同选理：割去$$s->1,s->2$$，得$$sum-(a_1+\frac{c_{1,2}}2)-(a_2+\frac{c_{1,2}}2)=b_1+b_2+d_{1,2}$$
3. $$1$$选文，$$2$$选理：割去$$s->2,1->2,1->t$$，得$$sum-(a_2+\frac{c_{1,2}}2)-(\frac{c_{1,2}}2+\frac{d_{1,2}}2)-(b_1+\frac{d_{1,2}}2)=a_1+b_2$$
4. $$1$$选理，$$2$$选文：割去$$s->1,2->1,2->t$$，得$$sum-(a_1+\frac{c_{1,2}}2)-(\frac{c_{1,2}}2+\frac{d_{1,2}}2)-(b_2+\frac{d_{1,2}}2)=a_2+b_1$$

### 代码

#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define Reg register
#define RI Reg int
#define Con const
#define CI Con int&
#define I inline
#define W while
#define N 100
#define min(x,y) ((x)<(y)?(x):(y))
#define INF 1e9
using namespace std;
int n,m,a[N+5][N+5],b[N+5][N+5];
class FastIO
{
private:
#define FS 100000
#define tn (x<<3)+(x<<1)
#define D isdigit(c=tc())
char c,*A,*B,FI[FS];
public:
I FastIO() {A=B=FI;}
Tp I void read(Ty& x) {x=0;W(!D);W(x=tn+(c&15),D);}
#undef D
}F;
class Dinic//Dinic跑网络流
{
private:
static const int Psz=N*N+2,Lsz=(N*N<<2)+(N*N<<3);int ee,lnk[Psz+5],cur[Psz+5],q[Psz+5],dep[Psz+5];
struct edge {int to,nxt,Cap;}e[Lsz+5];
I bool BFS()//BFS找增广路
{
RI i,k,H=1,T=1;memset(dep,0,sizeof(dep)),dep[q[1]=s]=1;W(H<=T&&!dep[t])
for(i=lnk[k=q[H++]];i;i=e[i].nxt) e[i].Cap&&!dep[e[i].to]&&(dep[q[++T]=e[i].to]=dep[k]+1);
return dep[t]?(memcpy(cur,lnk,sizeof(lnk)),true):false;
}
I int DFS(CI x,RI f)//DFS统计流量
{
if(!(x^t)||!f) return f;RI i,t,res=0;
for(i=cur[x];i;i=e[i].nxt)
{
if(cur[x]=i,(dep[x]+1)^dep[e[i].to]||!(t=DFS(e[i].to,min(f,e[i].Cap)))) continue;
if(e[i].Cap-=t,e[((i-1)^1)+1].Cap+=t,res+=t,!(f-=t)) break;
}return !res&&(dep[x]=-1),res;
}
public:
int s,t;I Dinic() {s=1,t=2;}I int P(CI x,CI y) {return (x-1)*m+y+2;}
I int MaxFlow() {RI res=0;W(BFS()) res+=DFS(s,INF);return res;}//求最大流
}D;
int main()
{