335 字
2 分钟
题解:P8191 [USACO22FEB] Moo Network G

很妙啊。

思路#

首先我们先退化为一维(即所有点的 yy 相同),如果有三个点 xa<xb<xcx_a<x_b<x_c 且我们需要从点 aa 到达点 cc,最优的策略是什么呢?

策略

如果直接从 aa 到 cc 连一条边的话,边权是 (xc−xa)2(x_c-x_a)^2 的。我们展开一下:

(xc−xa)2=(xc−xb+xb−xa)2=(xc−xb)2+(xb−xa)2+2(xc−xb)(xb−xa)(x_c-x_a)^2 = (x_c-x_b+x_b-x_a)^2 = (x_c-x_b)^2+(x_b-x_a)^2+2(x_c-x_b)(x_b-x_a)

显然连 (a,b)(a,b) 和 (b,c)(b,c) 是更优的。

现在我们来推广一下,因为 0≤y≤100 \le y \le 10,所以整个平面上最多只有 1111 条直线。我们先考虑点 a(xa,ya),b(xb,yb),c(xc,yc)a(x_a,y_a), b(x_b,y_b), c(x_c,y_c) 且 ya≠yb,yb=yc,xb<xc≤xay_a \not= y_b, y_b=y_c, x_b<x_c \le x_a。你会发现结论是一样的,连 (a,c)(a,c) 和 (c,b)(c,b) 是更优的。

我们考虑该保留哪些边呢?容易发现,每一头奶牛只需要与左右相邻的奶牛和前面每条横线上离它最近的那头牛相连即可。

这样总边数就是 11N11N 的,时间复杂度为 O(11Nlog⁡(11N))O(11N \log (11N))。

Code#

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=1e5+5;
struct node {
int x,y;
}a[maxn];
bool cmp(node x,node y) {
return x.x<y.x;
}
struct edge {
int u,v,w;
bool operator <(const edge &x) const {
return w<x.w;
}
};
int n,ans,id[15],fa[maxn];
vector<edge> e;
int find(int x) {
return fa[x]==x ? x : fa[x]=find(fa[x]);
}
signed main() {
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
for (int i=1;i<=n;i++)
cin>>a[i].x>>a[i].y,fa[i]=i;
sort(a+1,a+1+n,cmp);
memset(id,-1,sizeof(id));
for (int i=1;i<=n;i++) {
for (int j=0;j<=10;j++)
if (id[j]!=-1) {
int u=id[j];
int dx=a[i].x-a[u].x,dy=a[i].y-a[u].y;
e.push_back({u,i,dx*dx+dy*dy});
}
id[a[i].y]=i;
}
sort(e.begin(),e.end());
int cnt=0;
for (auto [u,v,w]:e) {
int fu=find(u),fv=find(v);
if (fu==fv) continue;
fa[fu]=fv;
ans+=w;
cnt++;
if (cnt==n-1) break;
}
cout<<ans;
return 0;
}
题解:P8191 [USACO22FEB] Moo Network G
https://banglee13.github.io/posts/p8191/
作者
banglee
发布于
2026-10-28
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类

换条路线

从其他文章中稳定抽取