회원가입
로그인
Toggle navigation
문제
문제
전체 문제
문제 출처
단계별로 풀어보기
알고리즘 분류
추가된 문제
문제 순위
문제
푼 사람이 한 명인 문제
아무도 못 푼 문제
최근 제출된 문제
최근 풀린 문제
랜덤
출처
ICPC
Olympiad
한국정보올림피아드
한국정보올림피아드시․도지역본선
전국 대학생 프로그래밍 대회 동아리 연합
대학교 대회
카카오 코드 페스티벌
Coder's High
ICPC
Regionals
World Finals
Korea Regional
Africa and the Middle East Regionals
Europe Regionals
Latin America Regionals
North America Regionals
South Pacific Regionals
문제집
대회
1
채점 현황
랭킹
게시판
그룹
더 보기
재채점 기록
블로그
강의
실험실
도움말
BOJ Stack
BOJ Book
전체
공지
자유
질문
오타/오역/요청
게시판 공지
홍보
업데이트
solved.ac
글쓰기
질문 도움말
자주묻는 질문
prim 알고리즘으로 풀었는데 틀렸습니다가 나오네요..
1197번 - 최소 스패닝 트리
tjgy9023
5년 전
0
예제는 잘나오는데.. 다익스트라 처럼 하는데 이거는 누적되지 않게 짰는데
어디서 틀린걸까요..
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; public class PrimMain { static int[] dist; static boolean[] visited; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken())+1; int M = Integer.parseInt(st.nextToken()); dist = new int[N]; visited = new boolean[N]; ArrayList<Edge>[] alists = new ArrayList[N]; for(int i = 0 ; i < N; i ++) { alists[i] = new ArrayList<>(); } for(int i = 0; i < M; i ++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int w = Integer.parseInt(st.nextToken()); alists[a].add(new Edge(b,w)); } prim(alists); int k = 0; for(int i = 1; i < N ; i++) { k += dist[i]; } System.out.println(k); } public static void prim(ArrayList<Edge>[] alist) { int startVertex = 1; PriorityQueue<Edge> pq = new PriorityQueue<>(new Comparator<Edge>() { @Override public int compare(Edge o1, Edge o2) { return o1.weigth - o2.weigth; } }); for(int i = 0; i < alist.length ; i++) dist[i] = Integer.MAX_VALUE; dist[startVertex] = 0; pq.add(new Edge(startVertex, dist[startVertex])); while(!pq.isEmpty()) { Edge edge = pq.poll(); int vertex = edge.vertex; if(visited[vertex]) continue; visited[vertex] = true; for(Edge e: alist[vertex]) { int destination = e.vertex; int layoverWeight = e.weigth; if(dist[destination] > layoverWeight) { dist[destination] = layoverWeight; pq.add(new Edge(destination, dist[destination])); } } } } } class Edge{ int vertex; int weigth; public Edge(int vertex, int weigth) { super(); this.vertex = vertex; this.weigth = weigth; } }
댓글을 작성하려면
로그인
해야 합니다.
tjgy9023 5년 전
예제는 잘나오는데.. 다익스트라 처럼 하는데 이거는 누적되지 않게 짰는데
어디서 틀린걸까요..