试题 历届试题 发现环
资源限制
时间限制:1.0s 内存限制:256.0MB
$Daily English
虽然世界充满苦难,但是苦难总是可以战胜的。
While the world is full of suffering,it is also full of overcoming it.
问题描述
小明的实验室有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
思路:
-
way1
树上两个节点之间加了一条边,使树形成了一个环。
要找到这个环,如果知道环上的两点,环的路径就更容易确定,所以首先会想到并查集。先用并查集来确定环上的两个点,一个作为起点和一个终点,然后dfs记录路径即可。 -
way2
把握住树上节点度的特点,不在环上的节点度必为1,
所以可以使用拓扑排序,不断删除与度为1节点相连的边,
最终剩下的节点(度>1)即为环上的点。
代码:
way1:并查集+dfs
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5+5;
struct Edge
{
int from;
int to;
int next;
} edge[N<<1];
int head[N],id;
bool vis[N];
int pre[N];
int s,e;
int k;
inline void add_edge(int from,int to)
{
//edge[id].from = from;
edge[id].to = to;
edge[id].next = head[from];
head[from] = id++;
}
void init()
{
memset(head,-1,sizeof(head));
id = 0;
}
int myFind(int x)
{
if(pre[x] == x)
return x;
return pre[x] = myFind(pre[x]);
}
int myUnion(int x,int y)
{
int fx = myFind(x);
int fy = myFind(y);
if(fx != fy)
{
pre[fx] = fy;
return 0;
}
return 1;
}
void dfs(int u,int cnt)
{
for(int i = head[u]; ~i; i = edge[i].next)
{
int to = edge[i].to;
if(!vis[to])
{
vis[to] = true;
pre[cnt+1] = to;
dfs(to,cnt+1);
}
else if(to == e && u != s)//保证不会一开始就走终点,而是走一圈
{
pre[++cnt] = e;
sort(pre,pre+cnt+1);
printf("%d",pre[0]);
for(int i = 1; i <= cnt; i++)
{
printf(" %d",pre[i]);
}
cnt--;
return;
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
pre[i] = i;
}
init();
bool flag = 0;
while(n--)
{
int x,y;
scanf("%d%d",&x,&y);
if(!flag)
{
flag = myUnion(x,y);
s = x;
e = y;
}
add_edge(x,y);
add_edge(y,x);
}
vis[s] = true;
vis[e] = true;
pre[0] = s;
dfs(s,0);
return 0;
}
way2:拓扑序
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5+5;
int d[N];
struct Edge
{
int from;
int to;
int next;
}edge[N<<1];
int head[N],id;
void init()
{
memset(head,-1,sizeof(head));
id = 0;
}
inline void add_edge(int from,int to)
{
edge[id].from = from;
edge[id].to = to;
edge[id].next = head[from];
head[from] = id++;
}
void topSort(int n)
{
queue<int>q;
for(int i = 1; i <= n; i++)
{
if(d[i] == 1)
{
q.push(i);
}
}
while(!q.empty())
{
int u = q.front();
d[u]--;
q.pop();
for(int i = head[u]; ~i; i = edge[i].next)
{
int to = edge[i].to;
d[to]--;
if(d[to] == 1)
{
q.push(to);
}
}
}
for(int i = 1; i <= n; i++)
{
if(d[i] > 1)
{
printf("%d ",i);
}
}
puts("");
}
int main()
{
int n;
scanf("%d",&n);
init();
for(int i = 0; i < n; i++)
{
int x,y;
scanf("%d%d",&x,&y);
d[x]++,d[y]++;
add_edge(x,y);
add_edge(y,x);
}
topSort(n);
return 0;
}