전공공부
[BOJ_21924] 도시건설 본문
설명
타입만 잘 지정하면 된다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static class Data implements Comparable<Data>{
int end;
int weight;
public Data(int end, int weight) {
this.end = end;
this.weight = weight;
}
@Override
public int compareTo(Data o) {
return this.weight - o.weight;
}
}
static boolean visited[];
static long max = 0;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(in.readLine()," ");
int V = Integer.parseInt(tk.nextToken()); //정점의 갯수
int E = Integer.parseInt(tk.nextToken()); //간선의 갯수
ArrayList<Data>[] list = new ArrayList[V+1];
visited = new boolean[V+1];
for(int i = 0;i<V+1;i++) {
list[i] = new ArrayList();
}
for(int i = 0; i < E; i++) {
tk = new StringTokenizer(in.readLine()," ");
int from = Integer.parseInt(tk.nextToken());
int to = Integer.parseInt(tk.nextToken());
int weight = Integer.parseInt(tk.nextToken());
list[from].add(new Data(to,weight));
list[to].add(new Data(from,weight));
max += weight;
}
PriorityQueue<Data> q = new PriorityQueue<Data>();
q.offer(new Data(1,0)); //자기 자신은 0
int cnt = 0;
long res = 0;
while(!q.isEmpty()) {
Data cur = q.poll();
if(visited[cur.end]) {
continue;
}
visited[cur.end] = true;
res += (long)cur.weight;
cnt++;
if(cnt == V) {
break;
}
for (int j = 0; j < list[cur.end].size(); j++) {
if(!visited[list[cur.end].get(j).end]) {
q.offer(new Data(list[cur.end].get(j).end,list[cur.end].get(j).weight));
}
}
}
if(cnt >= V) {
System.out.println(max - res);
}else{
System.out.println(-1);
}
}
}
21924번: 도시 건설
첫 번째 줄에 건물의 개수 $N$ $(3 \le N \le 10^5 )$와 도로의 개수 $M$ $(2 \le M \le min( {N(N-1) \over 2}, 5×10^5)) $가 주어진다. 두 번째 줄 부터 $M + 1$줄까지 건물의 번호 $a$, $b$ $(1 \le a, b \le N, a ≠ b)$와 두
www.acmicpc.net
'Study > Problem Solving' 카테고리의 다른 글
[BOJ_18352] 특정 거리의 도시 찾기 (0) | 2024.01.19 |
---|---|
[BOJ_14621] 나만 안되는 연애 (0) | 2024.01.14 |
[BOJ_1774] 우주신과의 교감 (1) | 2024.01.13 |
[BOJ_16398] 행성 연결 (0) | 2024.01.10 |
[BOJ_1647] 도시 분할 계획 (0) | 2024.01.08 |