[swexpert] 1251. 하나로 (java, 크루스칼, union-find)
728x90
반응형
import java.util.PriorityQueue;
import java.util.Scanner;
class Bridge implements Comparable<Bridge>{
int a;
int b;
double dist;
public Bridge(int a,int b, double dist) {
super();
this.a=a;
this.b=b;
this.dist = dist;
}
@Override
public int compareTo(Bridge o) {
if(this.dist<o.dist)return -1;
else if(this.dist>o.dist)return 1;
return 0;
}
}
public class S_1251_하나로_Solution {
static int t,n;
static PriorityQueue<Bridge> bridge;
static int[] xlist;
static int[] ylist;
static double answer,e;
static int[] parent;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
for (int tc = 1; tc <=t; tc++) {
n=sc.nextInt();
answer=0;
parent=new int[n+1];
for (int i = 1; i <=n; i++) {
parent[i]=i;
}
bridge=new PriorityQueue<>();
xlist=new int[n];
ylist=new int[n];
for (int i = 0; i < n; i++) {
xlist[i]=sc.nextInt();
}
for (int i = 0; i < n; i++) {
ylist[i]=sc.nextInt();
}
e=sc.nextDouble();
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int diffy=ylist[i]-ylist[j];
int diffx=xlist[i]-xlist[j];
double dis=Math.pow(diffy,2)+Math.pow(diffx, 2);
bridge.add(new Bridge(i+1,j+1,dis));
}
}
int len=bridge.size();
for (int i = 0; i < len; i++) {
Bridge cur=bridge.poll();
union(cur.a,cur.b,cur.dist);
}
System.out.printf("#%d %.0f\n",tc,answer);
}
}
private static int find(int x) {
if(x==parent[x])return x;
return parent[x]=find(parent[x]);
}
private static void union(int a, int b, double dist) {
a=find(a);
b=find(b);
if(a!=b) {
answer+=e*dist;
if(a<=b) {
parent[b]=a;
}else {
parent[a]=b;
}
}
}
}
728x90
반응형
'swexpert' 카테고리의 다른 글
[swexpert] 5644. 무선 충전 (구현, java) (0) | 2021.04.12 |
---|---|
[swexpert] 1263. 사람 네트워크2 (java, 플로이드 와샬) (0) | 2021.03.25 |
[swexpert] 3282. 0/1 knapsack (dp, java) (0) | 2021.03.23 |
[정보올림피아드] 1863. 종료 (Union-find, 시간제한) (0) | 2021.03.18 |
[swexpert] 3289. 서로소 집합 (java, union-find 함수) (0) | 2021.03.18 |
TAGS.