16502
문제
16502
접근
- 각 확률을 구하기 위해 노드를 만들어 푼다.
- dfs와 bfs 보다 구현으로 접근하는 것이 수월할 것 같다.
풀어보기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
static List<Node> list = new ArrayList<>();
static Map<String, Double> hash = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
int M = Integer.parseInt(bf.readLine());
for (int i = 0; i < M; i++) {
String[] temp = bf.readLine().split(" ");
String start = temp[0];
String end = temp[1];
double weight = Double.parseDouble(temp[2]);
list.add(new Node(start, end, weight));
}
hash.put("A", 0.25);
hash.put("B", 0.25);
hash.put("C", 0.25);
hash.put("D", 0.25);
for (int j = 0; j < N; j++) {
Map<String, Double> nextHash = new HashMap<>();
nextHash.put("A", 0.0);
nextHash.put("B", 0.0);
nextHash.put("C", 0.0);
nextHash.put("D", 0.0);
for (Node node : list) {
String start = node.start;
String end = node.end;
double weight = node.weight;
double currentProb = hash.get(start);
nextHash.put(end, nextHash.get(end) + currentProb * weight);
}
hash = nextHash;
}
System.out.printf("%.2f\n", hash.get("A") * 100);
System.out.printf("%.2f\n", hash.get("B") * 100);
System.out.printf("%.2f\n", hash.get("C") * 100);
System.out.printf("%.2f\n", hash.get("D") * 100);
}
static class Node {
String start;
String end;
Double weight;
Node(String start, String end, double weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
}
}
시행착오
- 노드를 만들고 해당 노드를 해쉬맵으로 담았지만 다음 값, 즉 한번 돌고 난 다음의 확률을 구하기 위해서는 또 다른 해쉬맵이 필요했다.