335 字
2 分钟
题解:P8191 [USACO22FEB] Moo Network G
很妙啊。
思路
首先我们先退化为一维(即所有点的 相同),如果有三个点 且我们需要从点 到达点 ,最优的策略是什么呢?
策略
如果直接从 到 连一条边的话,边权是 的。我们展开一下:
显然连 和 是更优的。
现在我们来推广一下,因为 ,所以整个平面上最多只有 条直线。我们先考虑点 且 。你会发现结论是一样的,连 和 是更优的。
我们考虑该保留哪些边呢?容易发现,每一头奶牛只需要与左右相邻的奶牛和前面每条横线上离它最近的那头牛相连即可。
这样总边数就是 的,时间复杂度为 。
Code
#include<bits/stdc++.h>using namespace std;#define int long longconst 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/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
最后更新于 ,距今已过 28 天
部分内容可能已过时