Posts 4386 make constellation
Post
Cancel

4386 make constellation

4386 make constellation

알고리즘(MST)

1
2
1. 모든 별들 사이의 거리를 구한 다음에, 두 별의 위치, 거리를 저장한 구조체 배열을 거리순으로 오름차순 정렬
2. 구조체 배열에서 하나씩 빼가며 크루스칼 시행 -> edge == numOfStar -1 이면 중지 후 출력

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define MAX_STAR 100

using namespace std;

typedef struct Star {
	double x;
	double y;
} Star;
typedef struct Distance {
	int first;
	int second;
	double distance;
	bool operator <(Distance d) {
		return distance < d.distance;
	}
} Distance;

Star star[MAX_STAR];
Distance dist[(MAX_STAR * (MAX_STAR+1))/2];
int numOfStar, checkStar[MAX_STAR], distIndex;
vector<vector<int>> set;

double getMinDistance();
void generateDistance();
bool unionFind(int a, int b);

int main() {
	cin >> numOfStar;
	for (int i = 0; i < numOfStar; i++) {
		cin >> star[i].x >> star[i].y;
	}
	for (int i = 0; i < numOfStar; i++)
		checkStar[i] = -1;

	cout.precision(20);
	cout << getMinDistance();
}

double getMinDistance() {
	generateDistance();
	sort(dist, dist + distIndex);

	double value = 0;
	int edge = 0;
	for (int i = 0; i < distIndex; i++) {
		if (unionFind(dist[i].first, dist[i].second)) {
			value += dist[i].distance;
			edge++;
		}
		if (edge == numOfStar - 1)
			break;
	}
	return value;
}

void generateDistance() {
	for (int i = 0; i < numOfStar; i++) {
		for (int j = i + 1; j < numOfStar; j++) {
			dist[distIndex].first = i;
			dist[distIndex].second = j;
			dist[distIndex++].distance = sqrt(((star[i].x - star[j].x) * (star[i].x - star[j].x)) + ((star[i].y - star[j].y) * (star[i].y - star[j].y)));
		}
	}
}

bool unionFind(int a, int b) {
	if (checkStar[a] == -1 && checkStar[b] == -1) {
		set.push_back({ a, b });
		checkStar[a] = set.size() - 1;
		checkStar[b] = set.size() - 1;
	}
	else if (checkStar[a] == -1) {
		set[checkStar[b]].push_back(a);
		checkStar[a] = checkStar[b];
	}
	else if (checkStar[b] == -1) {
		set[checkStar[a]].push_back(b);
		checkStar[b] = checkStar[a];
	}
	else if (checkStar[a] != checkStar[b]) {
		int temp = checkStar[b];
		for (int i = 0; i < set[temp].size(); i++) {
			set[checkStar[a]].push_back(set[temp][i]);
			checkStar[set[temp][i]] = checkStar[a];
		}
		set[temp].clear();
	}
	else
		return false;
	return true;
}
This post is licensed under CC BY 4.0 by the author.

3197 백조의 호수

4811 알약

Comments powered by Disqus.