1.问题引入:
2.编码实现:
package UnionFindAsseble;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TrafficProjectTest {
public static void main(String[] args) throws Exception {
//构建一个缓冲读取流BufferedReader
BufferedReader rd=new BufferedReader(new InputStreamReader(TrafficProjectTest.class.getClassLoader().getResourceAsStream("traffic_project.txt")));
//读取第一行数据20
int cities=Integer.parseInt(rd.readLine());
//构建一个并查集对象
UF uf=new UF(cities);
//读取第二行数据7
int roads=Integer.parseInt(rd.readLine());
//循环读取7条道路
for(int i=1;i<=roads;i++){
//读取每一条道路
String line=rd.readLine();
//通过空格堆读取到的字符串line进行分割,将分割后的数据存入数组str中
String[] str=line.split(" ");
//将城市存入并查集
//p为第一个城市
int p=Integer.parseInt(str[0]);
//q为第二个城市
int q=Integer.parseInt(str[1]);
//调用并查集对象的union方法让两个城市相通
uf.union(p, q);
}
//获取当前并查集中分组的数量-1即可求得还需修建的道路条数
int answer=uf.count()-1;
System.out.println("还需要修建"+ answer+"条道路才能实现畅通");
}
}
3.运行结果: