티스토리 뷰

Algorithm

백준_행성연결_16398_Prim

Young_J 2021. 1. 7. 23:50

// 알고리즘

1. 최소 스패닝 트리

 

2. 주어진 인접리스트를 이용하여 Prim알고리즘으로 해결

 

3. 결과값이 int범위를 초과하는 경우가 생길 수 있음.

더보기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class 행성연결_16398_prim {
	static int N, map[][];

	static class Point implements Comparable<Point> {
		int to;
		long cost;

		public Point(int start, long cost) {
			super();
			this.to = start;
			this.cost = cost;
		}

		@Override
		public int compareTo(Point o) {
			// TODO Auto-generated method stub
			return Long.compare(this.cost, o.cost);
		}

	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		map = new int[N][N];

		for (int i = 0; i < N; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine(), " ");
			for (int j = 0; j < N; j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
			}
		}

		long[] dist = new long[N];
		boolean[] v = new boolean[N];

		PriorityQueue<Point> pq = new PriorityQueue<Point>();
		Arrays.fill(dist, Long.MAX_VALUE);

		dist[0] = 0;
		pq.add(new Point(0, dist[0]));
		int cnt = 0;

		Point current = null;
		while (!pq.isEmpty()) {
			current = pq.poll();
			if (v[current.to]) {
				continue;
			}
			cnt++;
			if (cnt == N) {
				break;
			}

			v[current.to] = true;
			for (int i = 0; i < N; i++) {
				if (map[current.to][i] == 0)
					continue;
				if (!v[i] && map[current.to][i] != 0 && map[current.to][i] < dist[i]) {
					dist[i] = map[current.to][i];
					pq.add(new Point(i, dist[i]));
				}
			}

		}

		long ans = 0;

		for (Long l : dist) {
			ans += l;
		}

		System.out.println(ans);

	}

}

 

※ 자주 구현안해본 알고리즘이라 여러번 틀렸음. 다시 풀어볼 것.

'Algorithm' 카테고리의 다른 글

백준_나무 조각_2947  (0) 2021.01.17
백준_행성연결_16398_Kruskal  (0) 2021.01.09
백준_가장 긴 증가하는 부분수열2_12015  (0) 2021.01.06
백준_가장 긴 증가하는 부분수열_11053  (0) 2021.01.05
백준_오목_2615  (0) 2021.01.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/02   »
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
글 보관함