Then, think about what Prim algorithm does, not how it is usually implemented. The implementation here is in fact easier than normally
Moderator: Board moderators
1
77 123
30 52
93 96
89 32
89 70
71 55
40 79
64 10
30 80
62 19
98 67
8 42
57 32
22 27
38 1
52 89
43 74
2 8
82 65
67 20
43 22
95 22
48 16
6 25
86 75
3 96
43 85
93 69
61 4
81 53
84 43
15 20
22 34
26 35
33 28
19 67
19 79
8 45
51 13
86 0
18 68
82 47
16 3
0 80
39 18
5 22
65 26
21 70
66 92
14 65
46 6
21 46
80 32
86 35
67 6
42 29
14 71
55 77
1 3
38 14
82 71
65 41
5 12
3 77
22 67
40 59
48 81
63 63
45 25
78 32
26 83
18 96
45 99
31 56
45 30
80 47
7 1
18 81AC.
Never use float as a running variable.
#include <iostream>
#include <utility>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdio>
#define sqr(x) ((x)*(x))
#define max 500000
#define maxnode 1005
using namespace std;
typedef pair<float,float>ii;
vector<ii>co;
float round(float d)
{
return floor(d+0.5);
}
struct edges
{
int s,e;
float w;
};
edges ed[max];
int par[maxnode];
bool comp(edges e1,edges e2)
{
return (e1.w-e2.w)<1e-9;
}
int findpar(int x)
{
if(par[x]==x)
return x;
else
return par[x]=findpar(par[x]);
}
int main()
{
//freopen("input.txt","r",stdin);
int t,counter=0;cin>>t;
while(t!=0)
{
int n,r;
co.clear();
t--;counter++;
cin>>n>>r;
for(int i=1;i<=n;i++)par[i]=i;
for(int i=0;i<n;i++)
{
float x,y;
cin>>x>>y;
co.push_back(ii(x,y));
}
int c=-1;
for(int i=0;i<co.size();i++)
for(int j=i+1;j<co.size();j++)
{
c++;
ed[c].s=i+1;
ed[c].e=j+1;
ed[c].w=sqrt(sqr((float)co[i].first-co[j].first)+sqr((float)co[i].second-co[j].second));
}
sort(ed,ed+c+1,comp);
int s=n;
float road=0,rail=0;
for(int i=0;i<=c;i++)
{
int u=findpar(ed[i].s);
int v=findpar(ed[i].e);
if((ed[i].w-r)>1e-9 && u!=v)
{
rail+=ed[i].w;
par[v]=par[u];
}
else if(u!=v)
{
road+=ed[i].w;
par[v]=par[u];
s--;
}
}
road=round(road);
rail=round(rail);
cout<<"Case #"<<counter<<": "<<s<<" "<<road<<" "<<rail<<endl;
}
return 0;
}
Users browsing this forum: No registered users and 1 guest