板子来源
航神+涛神
心得
下午涛神给航神例会讲的dinic板子加了一行代码
本来1996ms的代码瞬间跑到了170ms
卧槽这dinic板子碉堡了我要总结一下
基本可过大部分卡Dinic的板子,如hdu4280
hdu4280实测大概跑7700ms(时限10000ms),
而那道题用ISAP跑的话大概5000多ms
回头再总结个ISAP的板子叭
网络流理解了原理之后当小黑盒使用就好
代码
以hdu6214 Smallest Minimum Cut 为例
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=210;
const int maxm=2e3+10;
int level[maxn];
int head[maxn],cnt;
int t,n,m;
int ss,ee;
struct edge{int v,nex;ll w;}e[maxm];
void init()
{
cnt=0;
memset(head,-1,sizeof head);
}
void add(int u,int v,ll w)
{
e[cnt].v=v;
e[cnt].w=w;
e[cnt].nex=head[u];
head[u]=cnt++;
}
bool bfs(int s,int t)
{
queue<int>q;
memset(level,0,sizeof level);
level[s]=1;
q.push(s);
while(!q.empty())
{
int x=q.front();
q.pop();
if(x==t)return 1;
for(int u=head[x];~u;u=e[u].nex)
{
int v=e[u].v;ll w=e[u].w;
if(!level[v]&&w)
{
level[v]=level[x]+1;
q.push(v);
}
}
}
return 0;
}
ll dfs(int u,ll maxf,int t)
{
if(u==t)return maxf;
ll ret=0;
for(int i=head[u];~i;i=e[i].nex)
{
int v=e[i].v;ll w=e[i].w;
if(level[u]+1==level[v]&&w)
{
ll MIN=min(maxf-ret,w);
w=dfs(v,MIN,t);
e[i].w-=w;
e[i^1].w+=w;
ret+=w;
if(ret==maxf)break;
}
}
if(!ret)level[u]=-1;//优化,防止重搜,说明u这一路不可能有流量了
return ret;
}
ll Dinic(int s,int t)
{
ll ans=0;
while(bfs(s,t))
ans+=dfs(s,INF,t);
return ans;
}
int main()
{
scanf("%d",&t);
//n个点 m条边
while(t--)
{
init();
scanf("%d%d",&n,&m);
scanf("%d%d",&ss,&ee);
ss--,ee--;
for(int j=0;j<m;++j)
{
int u,v;ll w;
scanf("%d%d%lld",&u,&v,&w);
u--,v--;
w=w*10000+1;
add(u,v,w);
add(v,u,0);//有向图反向边权为0 无向图反向边权为w
}
ll ans=Dinic(ss,ee);
printf("%lld\n",ans%10000);
}
return 0;
}