一、题目
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
小明的实验室有N台电脑,编号1~N。原本这N台电脑之间有N-1条数据链接相连,恰好构成一个树形网络。在树形网络上,任意两台电脑之间有唯一的路径相连。
不过在最近一次维护网络时,管理员误操作使得某两台电脑之间增加了一条数据链接,于是网络中出现了环路。环路上的电脑由于两两之间不再是只有一条路径,使得这些电脑上的数据传输出现了BUG。
为了恢复正常传输。小明需要找到所有在环路上的电脑,你能帮助他吗?
输入格式
第一行包含一个整数N。
以下N行每行两个整数a和b,表示a和b之间有一条数据链接相连。
对于30%的数据,1 <= N <= 1000
对于100%的数据, 1 <= N <= 100000, 1 <= a, b <= N
输入保证合法。
输出格式
按从小到大的顺序输出在环路上的电脑的编号,中间由一个空格分隔。
样例输入
5
1 2
3 1
2 4
2 5
5 3
样例输出
1 2 3 5
二、解题思路
1.使用并查集把点联系起来,当有一次输入两个点的根节点是一样的时候,就说明这两个点一定在这个环上面
2.这里我把这两个点,一个作为起点一个作为终点,使用深度遍历记录经历的结点,最后把所有点进行从小到大的排序后输出
3.这道题只得了三十分,应该是内存超限,以后再回头来整
三、代码实现
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int []root;//根节点数组
static int []sort;//记录每个点有没有被走过
static int [][]arr;//记录深度遍历的数组
static int n;
static int []point;//记录每次走的路径
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
n=scanner.nextInt();
root=new int[n+1];
arr=new int[n+1][n+1];
sort=new int[n+1];
point=new int[n];
int a;
for(int i=1;i<=n;i++) {//根节点初始化
root[i]=i;
}
for(int i=0;i<n;i++) {
int x=scanner.nextInt();
int y=scanner.nextInt();
arr[x][y]=arr[y][x]=1;//初始化深度遍历的数组
huihuan(x,y);
}
}
}
private static void huihuan(int x,int y) {//并查集设置各个根节点
if(panduan(x)!=panduan(y)) {
root[panduan(y)]=panduan(x);
}
else {//当根节点相同时,形成一个环,以这个节点作为终点,以根节点作为起点进行深度遍历
dfs(y,x,0);//以y为起点,x为终点进行深度遍历
}
}
private static int panduan(int x) {
if(x==root[x]) {
return x;
}
else {
root[x]=panduan(root[x]);
return root[x];
}
}
private static void dfs(int x,int y,int count) {
sort[x]=1;
point[count]=x;
if(x==y && count>1) {
int []fin=new int[count+1];
for(int i=0;i<=count;i++) {
fin[i]=point[i];
}
Arrays.sort(fin);//因为直接用point数组会按照一开始设置好的空间进行排序,有些没用到的就是0了,这里新建数组做排序
for(int i=0;i<=count;i++) {
System.out.print(fin[i]+" ");
}
return ;
}
for(int i=1;i<=n;i++) {
if(arr[x][i]==1&&sort[i]==0) {//如果数组上有标记,且这个点未走过就进入这个点
dfs(i,y,count+1);
sort[i]=0;//回溯的时候把这个点标记未走过
}
}
}
}
本文介绍了一种使用并查集算法解决网络环路问题的方法,通过深度优先搜索找到所有环路中的电脑编号,适用于小明实验室的网络维护场景。
704

被折叠的 条评论
为什么被折叠?



