网络最大流
有空再把这篇补得好看一些吧。。。
重载运算符。
重载小括号/仿函数。
算法具体就不讲了,存个HLPP的板子好了。
关于 gap 优化:
当
这里你可能有个问题:有没有可能其他高度为
其实细想一番,便能发现问题。
所有高度为
所以我觉得
关于桶优化
一个困扰了我两天的问题。
问题出在
虽然初始化后能由
按照没有桶优化前的最高标号预留推进,使用优先队列,这些点自然没有问题。但是使用桶之后,这些高度为
我的代码虽然是错的,但是能过了加强版的模板。不过它过不了普通模板。拿数据一测,发现边正着输入和反着输入跑出来的答案不一样。
很玄学。
后来发现问题后才明白,是因为有一些死点被遍历到的先后顺序不同了。
附一组检测这个问题的数据:
INPUT:
5 4 1 5
1 2 3
2 3 2
2 5 3
2 4 2
OUTPUT:
3
评测记录_网络最大流(该题数据规模为 #define 作了修改)。
评测记录_最大流_加强版。
#include<cstdio>
#include<queue>
#include<bitset>
#include<cstring>
using namespace std;
namespace Qza{
#define MAXN 1204
#define MAXM 240002
#define INF 2147483647
int h[MAXN],f[MAXN],gap[MAXN];
int en[MAXN],nex[MAXM],to[MAXM],w[MAXM];
struct Compare{
inline bool operator () (int x,int y) const{
return h[x]<h[y];
}
};
void add_edge(int x,int y,int v)
{
static int cnt=-1;
nex[++cnt]=en[x]; to[cnt]=y; en[x]=cnt; w[cnt]=v;
}
void bfs(int s,int t)
{
register int u,v;
queue<int> q;
bitset<MAXN> inque;
for(q.push(t),inque[t]=1,h[t]=0;!q.empty();) {
u=q.front(); inque[u]=0; q.pop();
for(int p=en[u];p!=-1;p=nex[p])
if(w[p^1] && !h[v=to[p]] && v!=t) h[v]=h[u]+1,q.push(v),inque[v]=1;
}
}
int HLPP(int s,int t,int n)
{
if(s==t) return INF;
bfs(s,t);
if(!h[s]) return 0;
register int u,v,flow,false_node=0;
priority_queue<int,vector<int>,Compare> q;
bitset<MAXN>inque;
h[s]=n;
for(int i=1;i<=n;++i) if(h[i]) ++gap[h[i]];
for(int p=en[s];p!=-1;p=nex[p]) {
v=to[p];
flow=w[p];
if(flow) {
f[s]-=flow; f[v]+=flow;
w[p]-=flow; w[p^1]+=flow;
if(!inque[v] && v!=t && v!=s) {
q.push(v); inque[v]=1;
}
}
}
while(!q.empty()) {
u=q.top(); inque[u]=0;
q.pop();
if(h[u]>=h[s]) continue;
for(int p=en[u]; f[u] && p!=-1 ;p=nex[p]) { // 推流。
if( !w[p] || h[v=to[p]]>=h[u] ) continue; // 玄学 >= :h[v]<h[u] 的 v ,只有h[v]=h[u]-1的边才有容量。
flow=min(f[u],w[p]);
f[u]-=flow; f[v]+=flow;
w[p]-=flow; w[p^1]+=flow;
if(!inque[v] && v!=t && v!=s) {
q.push(v); inque[v]=1;
}
}
if(!f[u]) continue;
if(!(--gap[h[u]]))
for(int i=1;i<=n;++i)
if(i!=s && i!=t && h[i]>h[u] && h[i]<n+1) h[i]=n+1,++false_node;
h[u]=n+1;
for(int p=en[u];p!=-1;p=nex[p])
if(w[p] && h[u]>h[v=to[p]]+1) h[u]=h[v]+1;
++gap[h[u]];
q.push(u); inque[u]=1;
if(false_node==n) return f[t];
}
return f[t];
}
int read()
{
char ch=getchar(); int x=0;
while(ch<'0' || ch>'9') ch=getchar();
while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=getchar();
return x;
}
void main()
{
memset(en,0xff,sizeof(en));
int n,m,s,t,u,v,c,maxflow;
n=read(); m=read(); s=read(); t=read();
for(int i=1;i<=m;++i) {
u=read(); v=read(); c=read();
add_edge(u,v,c);
add_edge(v,u,0);
}
maxflow=HLPP(s,t,n);
printf("%d",maxflow);
return ;
}
}
int main()
{
Qza::main();
return 0;
}