A root tree is a directed acyclic graph that contains one node (root),
from which there is exactly one path to any other node.A root tree is binary if each node has at most two outgoing arcs.
When a binary tree is painted on the plane, all arcs should be
directed from top to bottom. That is, each arc going from u to v must
meet the condition yu > yv.You’ve been given the coordinates of all tree nodes. Your task is to
connect these nodes by arcs so as to get the binary root tree and make
the total length of the arcs minimum. All arcs of the built tree must
be directed from top to bottom. InputThe first line contains a single integer n (2 ≤ n ≤ 400) — the number
of nodes in the tree. Then follow n lines, two integers per line:
xi, yi (|xi|, |yi| ≤ 103) — coordinates of the nodes. It is guaranteed
that all points are distinct. OutputIf it is impossible to build a binary root tree on the given points,
print “-1”. Otherwise, print a single real number — the total length
of the arcs in the minimum binary tree. The answer will be considered
correct if the absolute or relative error doesn’t exceed 10 - 6.
每个点拆成入点和出点,s到出点连容量为
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int s=1005,t=1006,mod=1006,oo=0x3f3f3f3f;
double c[500010],len[1010],ans;
int fir[1010],ne[500010],to[500010],w[500010],
que[1010],in[1010],minw[1010],fa[1010],
xx[410],yy[410],
n,num,tot;
void add(int u,int v,int x,double y)
{
num++;
ne[num*2]=fir[u];
fir[u]=num*2;
to[num*2]=v;
w[num*2]=x;
c[num*2]=y;
ne[num*2+1]=fir[v];
fir[v]=num*2+1;
to[num*2+1]=u;
w[num*2+1]=0;
c[num*2+1]=-y;
}
double dis(int u,int v)
{
return sqrt((xx[u]-xx[v])*(xx[u]-xx[v])+(yy[u]-yy[v])*(yy[u]-yy[v]));
}
bool spfa()
{
int hd=0,tl=1,u,v;
que[0]=s;
in[s]=1;
memset(len,127,sizeof(len));
len[s]=0;
memset(minw,0,sizeof(minw));
minw[s]=oo;
while (hd!=tl)
{
u=que[hd++];
hd%=mod;
for (int i=fir[u];i;i=ne[i])
if (w[i]&&len[v=to[i]]>len[u]+c[i])
{
len[v]=len[u]+c[i];
minw[v]=min(minw[u],w[i]);
fa[v]=i;
if (!in[v])
{
in[v]=1;
que[tl++]=v;
tl%=mod;
}
}
in[u]=0;
}
if (!minw[t]) return 0;
tot+=minw[t];
ans+=minw[t]*len[t];
for (int i=fa[t];i;i=fa[to[i^1]])
{
w[i]-=minw[t];
w[i^1]+=minw[t];
}
return 1;
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d%d",&xx[i],&yy[i]);
for (int i=1;i<=n;i++) add(s,i,2,0),add(i+n,t,1,0);
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
if (yy[i]>yy[j])
add(i,j+n,1,dis(i,j));
while (spfa());
if (tot<n-1) printf("-1\n");
else printf("%.8f\n",ans);
}