반응형
https://www.acmicpc.net/problem/14950
14950번: 정복자
서강 나라는 N개의 도시와 M개의 도로로 이루어졌다. 모든 도시의 쌍에는 그 도시를 연결하는 도로로 구성된 경로가 있다. 각 도로는 양방향 도로이며, 각 도로는 사용하는데 필요한 비용이 존재
www.acmicpc.net
1.문제설명
도시를 정복하기 위해 MST를 만들어야 하는 문제이다.
주의할 점은 한 도시를 정복한 이후부터 간선의 가중치가 t값만큼 증가해야한다.
첫 도시를 정복할 때 가중치가 포함되면 안된다.
Java로 Prim 알고리즘을 구현하기 위해서
자바 우선순위큐를 사용할 줄 알아야한다.
이때 custom class를 이용하기 때문에 Comparable을 implements 해주어야 한다.
2.문제풀이코드 C++
import java.util.*;
class Edge implements Comparable<Edge>{
// boolean canUse;
int x, y;
Edge(int x, int y){
// canUse = true;
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public int compareTo(Edge edge){
return Integer.compare(y, edge.y);
}
}
public class Main {
static int n,m,t;
static boolean ch[];
static ArrayList<Edge> adj[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
t = sc.nextInt();
PriorityQueue<Edge> Q = new PriorityQueue<>();
ch = new boolean[n+1];
adj = new ArrayList[n+1];
for(int i=0; i<=n; i++){
adj[i] = new ArrayList<Edge>();
}
for(int i=0; i<m; i++){
int a, b, c;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
adj[a].add(new Edge(b,c));
adj[b].add(new Edge(a,c));
}
Q.add(new Edge(1,0));
int cnt = 0;
int ans = 0;
while(!Q.isEmpty()){
Edge cur = Q.poll();
if(!ch[cur.x]){
ch[cur.x] = true;
ans += cur.y;
cnt++;
if(cnt>2){
ans += t*(cnt-2);
}
// System.out.println(ans);
for(Edge nx : adj[cur.x]) {
if (ch[nx.x] == false) {
Q.add(nx);
}
}
}
}
System.out.println(ans);
}
}
반응형
'Algorithm > problem' 카테고리의 다른 글
백준 1368번 : 물대기 - Java (0) | 2022.06.07 |
---|---|
백준 1946번 : 신입사원 - Java fastio, Arraylist , Collections.sort (0) | 2022.05.24 |
백준 2638번 : 치즈 Java (0) | 2022.05.20 |
백준 4803번 : 트리 - java DFS풀이와 Union & Find 풀이 (0) | 2022.04.30 |
백준 2696번 : 중앙값 구하기 Java (0) | 2022.04.23 |