1.给N个点 建立一支最小生成树
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=207;
int n,m;
int d[maxn][maxn];
int dis[maxn],ans;
bool v[maxn];
int main(){
while(scanf("%d",&n)!=EOF&&n) {
char a,b;
int m,x;
memset(d,0x3f3f3f,sizeof(d));
memset(v, 0, sizeof(v));
memset(dis,0x3f3f3f,sizeof(dis));
for(int i=1;i<n;i++) {
cin>>a>>m;
while(m--){
cin>>b>>x;
d[a-'A'][b-'A']=d[b-'A'][a-'A']=min(d[a-'A'][b-'A'],x);
//cout<<d[a-'A'][b-'A']<<endl;
}
}
for(int i=0;i<n;i++) d[i][i]=0;
dis[0]=0;
for(int i=1;i<n;i++){
int x=206;
for(int j=0;j<n;j++) {
if(!v[j]&&dis[j]<dis[x]) x=j;
}
v[x]=1;
for(int j=0;j<n;j++ ) {
if(!v[j]) dis[j]=min(dis[j],d[x][j]);
}
}
ans=0;
for(int i=1;i<n;i++) {
//cout<<dis[i]<<" ";
ans+=dis[i];
}
cout<<ans<<endl;
}
2.Networking
同上 不同的是下标一个是1一个是0
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=507;
int n,m;
int d[maxn][maxn];
int dis[maxn],ans;
bool v[maxn];
int main(){
while(cin>>n>>m&&n){
int a,b,c;
memset(d,0x3f3f3f,sizeof(d));
for(int i=1;i<=m;i++){
cin>>a>>b>>c;
d[a][b]=min(d[a][b],c);
d[b][a]=d[a][b];
}
for(int i=1;i<=n;i++){
d[i][i]=0;
}
memset(v, 0, sizeof(v));
memset(dis,0x3f3f3f,sizeof(dis));
dis[1]=0;
for(int i=1;i<n;i++){
int x=0;
for(int j=1;j<=n;j++) if(!v[j]&&dis[j]<dis[x]) x=j;
v[x]=1;
for(int j=1;j<=n;j++) if(!v[j]) dis[j]=min(dis[j],d[x][j]);
}
ans=0;
for(int i=2;i<=n;i++) {
//cout<<dis[i]<<" ";
ans+=dis[i];
}
cout<<ans<<endl;
}
}
3.Building a Space Station
依然是板子
要注意的是球心之间的距离 - 两个球的半径如果 < 0 则说明是覆盖的,此时的距离按照0计算
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define inf 0x7f7f7f7f
using namespace std;
struct node{
double x,y,z,r;
}q[101];
bool v[101];
double d[101][101],dis[101];
int main(){
int n;
while(scanf("%d",&n)&&n){
double s;
memset(d,0,sizeof(d));
for(int i=1;i<=n;i++) {
scanf("%lf %lf %lf %lf",&q[i].x,&q[i].y,&q[i].z,&q[i].r);
}
for(int i=1;i<n;i++){
for(int j=i+1;j<=n;j++){
s= sqrt((q[i].x-q[j].x)*(q[i].x-q[j].x)+(q[i].y-q[j].y)*(q[i].y-q[j].y)+(q[i].z-q[j].z)*(q[i].z-q[j].z))-q[i].r-q[j].r;
if(s>0) {
d[i][j]=d[j][i]=s;
}
else d[i][j]=d[j][i]=0;
}
}
for(int i=1;i<=n;i++){
d[i][i]=0;
}
memset(v, 0, sizeof(v));
memset(dis,0x7f7f7f7f,sizeof(dis));
dis[1]=0;
for(int i=1;i<n;i++){
int x=0;
for(int j=1;j<=n;j++) if(!v[j]&&dis[j]<dis[x]) x=j;
v[x]=1;
for(int j=1;j<=n;j++) if(!v[j]) dis[j]=min(dis[j],d[x][j]);
}
double ans=0;
for(int i=2;i<=n;i++) {
//cout<<dis[i]<<" ";
ans+=dis[i];
}
printf("%.3lf\n",ans);
}
}