7.19最小生成树测试题解
7.19最小生成树测试题解
A - Watering the Fields S
思路
- 计算任意两个点的距离平方,若符合要求则作为边权。
- 将所有边按边权从小到大排序。
- 从小到大依次选取边,若该边连接的两个点未连通则连接他们 。
若成功选出的边数可连通,则输出;否则输出
-1 。代码如下
#include <bits/stdc++.h> using namespace std; const int N=2e6; int f[N]; int n; long long c; struct node { int x,y; long long l; }a[N],s[N]; bool cmp(node x, node y) { return x.l<y.l; } int find(int x) { if (f[x]==x)return x; return f[x]=find(f[x]); } void init() { for(int i=1;i<=n;i++)f[i]=i; } int sqr(int x){return x*x;} int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n>>c; if(n==1||n==0) { cout<<0<<endl; return 0; } init(); int cnt=0; for(int i=1;i<=n;i++) { int x1,y1; cin>>x1>>y1; s[i]={x1,y1}; for(int j=1;j<i;j++) { int x2=s[j].x,y2=s[j].y; long long l=sqr(x1-x2)+sqr(y1-y2); if(l>=c)a[++cnt]={i,j,l}; } } sort(a+1,a+1+cnt,cmp); int p=0; int s=0; bool flag=false; for(int i=1;i<=n*(n-1)/2;i++) { int fx=find(a[i].x),fy=find(a[i].y); if(fx==fy)continue; f[fx]=fy; p++; s+=a[i].l; if(p==n-1) { cout<<s<<endl; flag=true; break; } } if(!flag) cout<<-1<<endl; return 0; }
B - Out of Hay S
思路
- 将所有边按边权从小到大排序。
- 从小到大依次选取边,若该边连接的两个点未连通则连接他们 。
若成功选出的边数可连通,则输出;否则输出
-1 。代码如下
#include <bits/stdc++.h> using namespace std; const int N=2000,M=1e4+5; int f[N]; int n,m; struct node { int x,y,l; }a[M]; bool cmp(node x, node y) { return x.l<y.l; } int find(int x) { if (f[x]==x)return x; return f[x]=find(f[x]); } void init() { for(int i=1;i<=n;i++)f[i]=i; } int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n; if(n==1) { cout<<0<<endl; return 0; } init(); int m; cin>>m; for(int i=1;i<=m;i++) { int x,y,l; cin>>x>>y>>l; a[i]={x,y,l}; } sort(a+1,a+1+m,cmp); int s=0,cnt=0; bool flag=false; for(int i=1;i<=m;i++) { int fx=find(a[i].x),fy=find(a[i].y); if(fx==fy)continue; f[fx]=fy; cnt++; s=max(s,a[i].l); if(cnt==n-1) { cout<<s<<endl; flag=true; break; } } if(!flag) cout<<"No\n"; return 0; }
C - Jungle Roads
思路
- 先将字母转化为数字
- 其余同A
-
数组要开
2×10^6 代码如下
#include <bits/stdc++.h> using namespace std; const int N=2000,M=1e4+5; int f[N]; int n,m; struct node { int x,y,l; }a[M]; bool cmp(node x, node y) { return x.l<y.l; } int find(int x) { if (f[x]==x)return x; return f[x]=find(f[x]); } void init() { for(int i=1;i<=n;i++)f[i]=i; } int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); while(cin>>n&&n) { if(n==1) { cout<<0<<endl; continue; } init(); int m=0; for(int i=1;i<n;i++) { int k; char p; cin>>p>>k; int x=p-'A'+1; for(int j=1;j<=k;j++) { int l; char q; cin>>q>>l; int y=q-'A'+1; a[++m]={x,y,l}; } } sort(a+1,a+1+m,cmp); int s=0,cnt=0; bool flag=false; for(int i=1;i<=m;i++) { int fx=find(a[i].x),fy=find(a[i].y); if(fx==fy)continue; f[fx]=fy; cnt++; s+=a[i].l; if(cnt==n-1) { // cerr<<"ans:"; cout<<s<<endl; flag=true; break; } } if(!flag) cout<<"No\n"; } return 0; }