import java.util.HashMap;
import java.util.Map;
public class NuclearRod {
/**
* @param n the number of rods
* @param edges An array of Strings, pairs, like "12 23" meaning 12 and 23 is connected.
* @return the cost
*/
public static int countComponents(int n, String[] edges) {
Map<Integer, Integer> roots = new HashMap<>();
for (int i = 0; i < n; i++) {
roots.put(i, i);
}
int connectedNumber = n;
for (int i = 0; i < edges.length; i++) {
String[] pair = edges[i].split(" ");
int root1 = find(roots, Integer.valueOf(pair[0]));
int root2 = find(roots, Integer.valueOf(pair[1]));
if (root1 != root2) {
//union root2 into root1
roots.put(root2, root1);
connectedNumber--;
}
}
//calculate the number of rods in each fused part
int[] connected = new int[n];
for (Integer id : roots.keySet()) {
int root = find(roots, id);
connected[root]++;
}
//calculate the cost
int cost = 0;
for (int i = 0; i < connected.length; i++) {
cost += (int)Math.ceil(Math.sqrt((double)connected[i]));
}
return cost;
}
public static int find(Map<Integer, Integer> roots, int id) {
while (roots.get(id) != id) {
//change father to grandfather
roots.put(id, roots.get(roots.get(id)));
id = roots.get(id);
}
return id;
}
public static void main(String[] args) {
// 0 3
// | |
// 1 --- 2 4
String[] rods = new String[] {"0 1", "1 2", "3 4"};
int cost = countComponents(5, rods);
System.out.println(cost); //4
}
}
Nulear Rods
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 经常给家长讲,孩子的小学时期是养成的教育,是习惯培养的最佳时期;初中的孩子,学习心态决定一切,不管小学时期成绩如何...