홍시홍의 프로그래밍

[백준 4343] Arctic Network 본문

알고리즘 문제풀이/백준

[백준 4343] Arctic Network

홍시홍 2020. 3. 2. 21:40

https://www.acmicpc.net/problem/4343

 

4343번: Arctic Network

The first line of input contains N, the number of test cases. The first line of each test case contains 1 <= S <= 100, the number of satellite channels, and S < P <= 500, the number of outposts. P lines follow, giving the (x,y) coordinates of each outpost

www.acmicpc.net

 

요구사항

전초 기지를 모두 이을 때 최소가 되는 D 구하기

 

풀이

최소가 되는 D를 구하기 위해서 제일 작은거를 위성 수 만큼 연결 해줄때 제일 마지막으로 연결된 것이 정답이다.

Union-Find와 힙을 이용하여 정답 구하기

 

#include <iostream>
#include <queue>
#include <math.h>
#include <algorithm>
#include <functional>
using namespace std;
typedef pair<double, pair<int, int> > q;
typedef long long ll;
struct go {
	int x;
	int y;
};
int n, m;
go map[550];
int parent[550];
int Find(int a) {
	if (parent[a] == a) return a;
	else return parent[a] = Find(parent[a]);
}
bool Union(int a, int b) {
	a = Find(a);
	b = Find(b);
	if (a == b) return false;
	if (a != b) {
		parent[a] = b;
		return true;
	}

}
int main() {
	int t;
	scanf("%d", &t);
	for (int tc = 1; tc <= t; tc++) {
		priority_queue<q> pq;
		scanf("%d%d", &n, &m);
		for (int i = 1; i <= m; i++) {
			int x, y;
			parent[i] = i;
			scanf("%d%d", &x, &y);
			map[i].x = x;
			map[i].y = y;
		}
		for (int i = 1; i <= m; i++) {
			for (int j = i + 1; j <= m; j++) {
				int xdist = abs((map[i].x - map[j].x)) * abs((map[i].x - map[j].x));
				int ydist = abs((map[i].y - map[j].y)) * abs((map[i].y - map[j].y));
				double dist = sqrt(xdist + ydist);
				pq.push(make_pair(-dist,make_pair(i,j)) ) ;
			}
		}
		double ans;
		int first_value;
		int second_value;
		while (true) {
			//cout << "A "<<n << endl;
			ans = -pq.top().first;
			first_value = pq.top().second.first;
			second_value = pq.top().second.second;
			pq.pop();
			//cout << ans << endl;
			if (Union(first_value, second_value)) {

				n--;
			}
			if (n == 0)
				break;
		}
		printf("%.2f\n", ans);
	}
}

 

 

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 1620] 나는야 포켓몬 마스터  (0) 2020.03.02
[백준 10774] 저지  (0) 2020.03.02
[백준 1377] 버블 소트  (0) 2020.02.29
[백준 1715] 카드 정렬하기  (0) 2020.02.29
[백준 1655] 가운데를 말해요  (0) 2020.02.29
Comments