题目地址:HDU 3452
最小割水题。源点为根节点,再另设一汇点,汇点与叶子连边。对叶子结点的判断是看度数是否为1.
代码如下:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
int head[3000], source, sink, nv, cnt, deg[2000];
int cur[3000], num[3000], d[3000], pre[3000];
struct node
{
int u, v, cap, next;
} edge[1000000];
void add(int u, int v, int cap)
{
edge[cnt].v=v;
edge[cnt].cap=cap;
edge[cnt].next=head[u];
head[u]=cnt++;
edge[cnt].v=u;
edge[cnt].cap=0;
edge[cnt].next=head[v];
head[v]=cnt++;
}
void bfs()
{
memset(num,0,sizeof(num));
memset(d,-1,sizeof(d));
queue<int>q;
q.push(sink);
d[sink]=0;
num[0]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
if(d[v]==-1)
{
d[v]=d[u]+1;
num[d[v]]++;
q.push(v);
}
}
}
}
int isap()
{
memcpy(cur,head,sizeof(cur));
int flow=0, u=pre[source]=source, i;
bfs();
while(d[source]<nv)
{
if(u==sink)
{
int f=INF, pos;
for(i=source; i!=sink; i=edge[cur[i]].v)
{
if(f>edge[cur[i]].cap)
{
f=edge[cur[i]].cap;
pos=i;
}
}
for(i=source; i!=sink; i=edge[cur[i]].v)
{
edge[cur[i]].cap-=f;
edge[cur[i]^1].cap+=f;
}
flow+=f;
u=pos;
}
for(i=cur[u]; i!=-1; i=edge[i].next)
{
if(d[edge[i].v]+1==d[u]&&edge[i].cap)
break;
}
if(i!=-1)
{
cur[u]=i;
pre[edge[i].v]=u;
u=edge[i].v;
}
else
{
if(--num[d[u]]==0) break;
int mind=nv;
for(i=head[u]; i!=-1; i=edge[i].next)
{
if(mind>d[edge[i].v]&&edge[i].cap)
{
mind=d[edge[i].v];
cur[u]=i;
}
}
d[u]=mind+1;
num[d[u]]++;
u=pre[u];
}
}
return flow;
}
int main()
{
int n, i, u, v, w;
while(scanf("%d%d",&n,&source)!=EOF&&n&&source)
{
memset(head,-1,sizeof(head));
memset(deg,0,sizeof(deg));
cnt=0;
sink=n+1;
nv=sink+1;
for(i=1;i<n;i++)
{
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
deg[u]++;
deg[v]++;
}
for(i=1;i<=n;i++)
{
if(i!=source&°[i]==1)
{
add(i,sink,INF);
}
}
printf("%d\n",isap());
}
return 0;
}