prime
#include<stdio.h>
#include<string.h>
#include<math.h>
#define MAX 100000
#define inf 0x6fffff
double map[111][111],dis[11111],count,x[111],y[111];
int i,j,m,n,visit[1111],k;
double distance(int i,int j)
{
double len=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
if(len<10||len>1000) len=inf;
return len;
}
double prime()
{
memset(visit,0,sizeof(visit));
for(i=1; i<=m; i++)
{
dis[i]=map[1][i];
}
visit[1]=1;
count=0;
for(i=1; i<m; i++)
{
double min=MAX;
k=0;
for(j=1; j<=m; j++)
{
if(!visit[j]&&min>dis[j])
{
min=dis[j];
k=j;
}
}
visit[k]=1;
count+=min;
for(j=1; j<=m; j++)
{
if(!visit[j]&&dis[j]>map[k][j])
dis[j]=map[k][j];
}
}
return count;
}
int main()
{ int a,b,l,p,d;
scanf("%d",&n);
while(n--)
{scanf("%d",&m);
for(i=1;i<=m;i++)
for(j=1;j<=m;j++)
map[i][j]=inf;
for(i=1;i<=m;i++)
{scanf("%lf%lf",&x[i],&y[i]);
map[i][i]=0;
for(j=1;j<=i;j++)
{map[i][j]=map[j][i]=distance(i,j);/*printf("%lf\n",distance(i,j));*/}
}
double sum=prime();
if(sum==100000) printf("oh!\n");
else printf("%.1lf\n",sum*100);
}
}
kruskal
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
double distance(double a,double b,double c,double d)
{
return sqrt((a-c)*(a-c)+(b-d)*(b-d));
}
struct e
{
int st,ed;
double pri;
}a[100100];
int cmp(e a,e b)
{
return a.pri<b.pri;
}
int pre[110];
void init(int n)
{
for(int i=1;i<=n;i++)
pre[i]=i;
}
int find(int x)
{
while(x!=pre[x])
x=pre[x];
return x;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
init(n);
double x[110],y[110];
for(int i=1;i<=n;i++)
scanf("%lf%lf",&x[i],&y[i]);
int k=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
// printf("%d %d %f\n",i,j,distance(x[i],y[i],x[j],y[j]));
if(i!=j){
if(distance(x[i],y[i],x[j],y[j])<=1000&&distance(x[i],y[i],x[j],y[j])>=10)
{//printf("%d %d %f\n",i,j,distance(x[i],y[i],x[j],y[j]));
a[k].st=i;
a[k].ed=j;
a[k++].pri=distance(x[i],y[i],x[j],y[j]);
}
}
}
}
sort(a,a+k,cmp);
// for(int i=0;i<k;i++)
// printf("%d %d %f\n",a[i].st,a[i].ed,a[i].pri);
double sum=0;
int cas=0;
for(int i=0;i<k;i++)
{
int dx=find(a[i].st);
int dy=find(a[i].ed);
if(dx!=dy){
pre[dx]=dy;
cas++;
sum+=a[i].pri;
}
}
if(cas==n-1)
printf("%.1f\n",sum*100);
else printf("oh!\n");
}
}