RT,最小费用最大流TLE了
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
inline ll read()
{
ll x = 0; bool op = 0;
char c = getchar();
while(!isdigit(c))op |= (c == '-'), c = getchar() ;
while(isdigit(c))x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
return op ? -x : x;
}
const int N = 810;
const int M = N * N * 2;
const int S = 801;
const int T = 802;
const int INF = 1e9;
int n, tot = 1, maxflow;
int head[N], to[M], nxt[M], flow[M], increase[N], pre[N];
double maxcost;
double dis[N], edge[M];
bool vis[N];
struct node
{
int x, y;
}a[N];
double distances(int x, int y)
{
int tmp1 = pow(a[x].x - a[y].x, 2);
int tmp2 = pow(a[x].y - a[y].y, 2);
return sqrt(tmp1 + tmp2);
}
void addedge(int u, int v, int f, double w)
{
to[++tot] = v;
edge[tot] = w;
flow[tot] = f;
nxt[tot] = head[u];
head[u] = tot;
return ;
}
void in()
{
n = read();
for(int i = 1; i <= n; i++)
{
a[i].x = read(); a[i].y = read();
}
return ;
}
void build()
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(j == i)
continue;
if(a[i].y > a[j].y)
{
addedge(i, j + n, INF, distances(i, j));
addedge(j + n, i, 0, -distances(i, j));
}
}
}
for(int i = 1; i <= n; i++)
{
addedge(S, i, 2, 0);
addedge(i, S, 0, 0);
addedge(i + n, T, 1, 0);
addedge(T, i + n, 0, 0);
}
return ;
}
bool spfa()
{
memset(vis, false, sizeof(vis));
dis[T] = INF;
for(int i = 1; i <= n * 2; i++)
dis[i] = INF;
queue<int> q;
dis[S] = 0; increase[S] = INF; vis[S] = true;
q.push(S);
while(q.empty() == false)
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i; i = nxt[i])
{
if(flow[i] == 0 || dis[to[i]] <= dis[u] + edge[i])
continue;
dis[to[i]] = dis[u] + edge[i];
increase[to[i]] = min(increase[u], flow[i]);
pre[to[i]] = i;
if(vis[to[i]] == false)
{
vis[to[i]] = true;
q.push(to[i]);
}
}
}
return dis[T] < INF;
}
void update()
{
int cur = T;
while(cur != S)
{
int last = pre[cur];
flow[last] -= increase[T];
flow[last ^ 1] += increase[T];
cur = to[last ^ 1];
}
maxflow += increase[T];
maxcost += increase[T] * dis[T];
return ;
}
void solve()
{
while(spfa() == true)
update();
if(maxflow < n - 1)
{
printf("-1");
return ;
}
printf("%.8lf", maxcost);
return ;
}
int main()
{
in();
build();
solve();
return 0;
}