版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/88533297
问题描述
小明的实验室有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
题解:裸的强连通图
#include<bits/stdc++.h>
using namespace std;
#define clr(a,b) memset(a,b,sizeof(a))
typedef long long ll;
const int maxn=100000+2;
const int minn=100;
const double eps=1e-6;
const int inf=0x3f3f3f3f3f3f;
int n,vis[maxn],loop[maxn];
vector<int> tmap[maxn];
set<int> ans;
stack<int> sa;
void Tarjan(int x,int pre,int dep)
{
sa.push(x);vis[x]=1;
for(int i=0;i<tmap[x].size();++i)
{
int y=tmap[x][i];
if(y==pre){continue;}
if(!vis[y]){ Tarjan(y,x,dep+1); if(!loop[y])sa.pop();}
else if(!loop[y])
{
ans.insert(y);
while(sa.top()!=y)
{
int tm=sa.top();sa.pop();
loop[tm]=1;
ans.insert(tm);
}
}
}
return ;
}
int main()
{
// freopen("input3.txt","r",stdin);
scanf("%d",&n);
int a,b;
while(n--)
{
scanf("%d%d",&a,&b);
tmap[a].push_back(b);
tmap[b].push_back(a);
}
Tarjan(1,0,0);
set<int>::iterator it=ans.begin();
for(;it!=ans.end();++it)
{
cout<<*it<<" ";
}
return 0;
}