题目链接:Drainage Ditches
和 HDU1532 一样,现提供另一种代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define INF 9999999
struct Node{
int to;
int w;
int ne;
}e[1000];
int head[1000],deth[1000];
int n,m,x,y,val,cnt;
queue<int>q;
void init()
{
cnt = 0;
memset(head,-1,sizeof(head));
while(!q.empty())
q.pop();
}
void add(int u,int v,int val)
{
e[cnt].to = v;
e[cnt].w = val;
e[cnt].ne = head[u];
head[u] = cnt ++;
}
int bfs()
{
memset(deth,0,sizeof(deth));
deth[1] = 1;
q.push(1);
while(!q.empty())
{
int k = q.front();
q.pop();
for(int i=head[k];~i;i=e[i].ne)
{
int t = e[i].to;
if(e[i].w >0 && deth[t] == 0)
{
deth[t] = deth[k] + 1;
q.push(t);
}
}
}
if(deth[m] == 0)
return 0;
return 1;
}
int dfs(int u,int dist)
{
if(u == m)
return dist;
for(int i=head[u];~i;i=e[i].ne)
{
if(deth[e[i].to] == deth[u] + 1 && e[i].w != 0)
{
int di = dfs(e[i].to,min(dist,e[i].w));
if(di>0)
{
e[i].w -= di;
e[i^1].w += di;
return di;
}
}
}
return 0;
}
long long dinic()
{
long long ans = 0;
while(bfs())
while(int di = dfs(1,INF))
ans += di;
cout<<ans<<endl;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=1;i<=n;i++)
{
scanf("%d%d%d",&x,&y,&val);
add(x,y,val);
add(y,x,0);
}
dinic();
}
return 0;
}
上面这种代码会多次调用 dfs 要慢一点(以HDU 1532 为例。。。poj1273 数据有点水,都是 0 s 。。。
嗯。。另一种代码(当前弧优化?!
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define maxn 2000
struct Node{
int w;
int to;
int ne;
}e[maxn<<2];
int head[maxn],deth[maxn];
int n,m,x,y,val,cnt;
void init()
{
cnt = 0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int val)
{
e[cnt].w = val;
e[cnt].ne = head[u];
e[cnt].to = v;
head[u] = cnt ++;
}
int bfs()
{
queue<int>q;
memset(deth,0,sizeof(deth));
deth[1] = 1;
q.push(1);
while(!q.empty())
{
int k = q.front();
q.pop();
for(int i=head[k];~i;i=e[i].ne)
{
int tt = e[i].to;
if(deth[tt] == 0 && e[i].w )
{
deth[tt] = deth[k] + 1;
q.push(tt);
}
}
}
if(deth[m] == 0)
return 0;
return 1;
}
int dfs(int u,int dist)
{
if(u == m)
return dist;
int temp = dist;
for(int i=head[u];~i;i=e[i].ne)
{
int t = e[i].to;
if(deth[t] == deth[u] + 1 && e[i].w)
{
int di ;
if(di = dfs(t,min(e[i].w ,temp)))
{
e[i].w -= di;
e[i^1].w += di;
temp -= di;
if(!temp)
return dist;
}
}
}
return dist - temp;
}
int dinic()
{
int ans = 0;
while(bfs())
{
while(int di = dfs(1,1e9))
ans += di;
}
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=1;i<=n;i++)
{
scanf("%d%d%d",&x,&y,&val);
add(x,y,val);
add(y,x,0);
}
printf("%d\n",dinic());
}
return 0;
}
这样还是蛮快的嘛