File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+
5+ public class boj21924 {
6+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
7+ static StringTokenizer st;
8+ static void nextLine () throws Exception {st = new StringTokenizer (br .readLine ());}
9+ static int nextInt() {return Integer . parseInt(st. nextToken());}
10+
11+ static int N , M , cnt = 0 ;
12+ static long answer;
13+ static ArrayList<ArrayList<Node > > graph = new ArrayList<> ();
14+ static boolean [] visited;
15+ public static void main(String [] args) throws Exception {
16+ nextLine();
17+ N = nextInt();
18+ M = nextInt();
19+ visited = new boolean [N + 1 ];
20+ for (int i = 0 ; i <= N ; i++ ) graph. add(new ArrayList<Node > ());
21+ for (int i = 0 ; i < M ; i++ ) {
22+ nextLine();
23+ int a = nextInt();
24+ int b = nextInt();
25+ int c = nextInt();
26+ graph. get(a). add(new Node (b, c));
27+ graph. get(b). add(new Node (a, c));
28+ answer += c;
29+ }
30+ dijkstra();
31+
32+ if (cnt == N ) System . out. println(answer);
33+ else System . out. println(- 1 );
34+ }
35+
36+ static void dijkstra() {
37+ PriorityQueue<Node > pq = new PriorityQueue<> ((o1,o2) - > o1. c- o2. c);
38+ pq. offer(new Node (1 , 0 ));
39+
40+ while (! pq. isEmpty()) {
41+ Node cur = pq. poll();
42+ if (visited[cur. v]) continue ;
43+ visited[cur. v] = true ;
44+ answer -= cur. c;
45+ cnt++ ;
46+ for (Node next : graph. get(cur. v)) {
47+ if (visited[next. v]) continue ;
48+ pq. offer(next);
49+ }
50+ }
51+ }
52+
53+ static class Node {
54+ int v, c;
55+ public Node (int v , int c ) {
56+ this . v = v;
57+ this . c = c;
58+ }
59+ }
60+ }
61+ ```
You can’t perform that action at this time.
0 commit comments