## 前置姿势

### 多路增广的费用流

#### 代码

bool spfa(){
memset(dis,0x3f,sizeof dis);
while(!q.empty())q.pop();
dis[s]=0,book[s]=true;q.push(s);
while(!q.empty()){
int x=q.front();q.pop();
trav(i,x){
int ver=e[i].to;
if(e[i].cap&&dis[ver]>dis[x]+e[i].cost){
dis[ver]=dis[x]+e[i].cost;
if(!book[ver]){
book[ver]=true;
q.push(ver);
}
}
}
book[x]=false;
}
return dis[t]<1e9;
}

int dfs(int x,int pref){
if(x==t||!pref)return pref;
int temp=0,flow=0;insta[x]=true;
for(int &i=cur[x];i;i=e[i].nxt){
int ver=e[i].to;if(insta[ver])continue;
if(dis[ver]==dis[x]+e[i].cost&&(temp=dfs(ver,std::min(pref,e[i].cap)))){
e[i].cap-=temp;
e[i^1].cap+=temp;
flow+=temp;
pref-=temp;
mincost+=temp*e[i].cost;
if(!pref)break;
}
}
insta[x]=false;
return flow;
}

void ek(){
while(spfa())maxflow+=dfs(s,1e9);
}


## 代码

#include <bits/stdc++.h>

#define rin(i,a,b) for(int i=(a);i<=(b);++i)
#define irin(i,a,b) for(int i=(a);i>=(b);--i)
#define trav(i,a) for(int i=head[a];i;i=e[i].nxt)
#define Size(a) (int)a.size()
#define pb push_back
#define mkpr std::make_pair
#define fi first
#define se second
#define lowbit(a) ((a)&(-(a)))
typedef long long LL;

using std::cerr;
using std::endl;

int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return x*f;
}

const int MAXN=1005;

struct Edge{
int to,nxt,cap,cost;
}e[MAXN*20];

inline void add_edge(int bg,int ed,int ca,int co){
++ecnt;
e[ecnt].to=ed;
e[ecnt].cap=ca;
e[ecnt].cost=co;
}

int maxflow,cur[MAXN<<1];
LL mincost,dis[MAXN<<1];
bool book[MAXN<<1],insta[MAXN<<1];
std::queue<int> q;

bool spfa(){
memset(dis,0x3f,sizeof dis);
while(!q.empty())q.pop();
dis[s]=0,book[s]=true;q.push(s);
while(!q.empty()){
int x=q.front();q.pop();
trav(i,x){
int ver=e[i].to;
if(e[i].cap&&dis[ver]>dis[x]+e[i].cost){
dis[ver]=dis[x]+e[i].cost;
if(!book[ver]){
book[ver]=true;
q.push(ver);
}
}
}
book[x]=false;
}
return dis[t]<1e18;
}

int dfs(int x,int pref){
if(x==t||!pref)return pref;
int temp=0,flow=0;insta[x]=true;
for(int &i=cur[x];i;i=e[i].nxt){
int ver=e[i].to;if(insta[ver])continue;
if(dis[ver]==dis[x]+e[i].cost&&(temp=dfs(ver,std::min(pref,e[i].cap)))){
e[i].cap-=temp;
e[i^1].cap+=temp;
flow+=temp;
pref-=temp;
mincost+=1ll*temp*e[i].cost;
if(!pref)break;
}
}
insta[x]=false;
return flow;
}

void ek(){
while(spfa())maxflow+=dfs(s,1e9);
}

int main(){
int x0=n*2+1,x1=x0+1,x2=x1+1,x3=x2+1;
s=x3+1,t=s+1;
rin(i,1,n){
}
rin(i,1,n){
}
ek();
printf("%lld\n",-mincost);
return 0;
}


posted on 2019-06-05 19:15  ErkkiErkko  阅读(101)  评论(0编辑  收藏

• 随笔 - 91
• 文章 - 0
• 评论 - 20