第八届蓝桥杯C/C++程序设计本科B组决赛 ——发现环(编程大题_签到题_tarjan判环)

标题:发现环

小明的实验室有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 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <queue>
 6 #include <stack>
 7 #include <vector>
 8 #include<math.h>
 9 #include <string.h>
10 #include<deque>
11 using namespace std;
12 #define inf 0x3f3f3f3f
13 #define maxn 10000000
14 const double pi=acos(-1.0);
15 #define ll long long
16 #define N 100008
17 vector<int>G[N];
18 int dfn[N]={0},lowcost[N]={0};
19 deque<int>st;
20 
21 int inst[N]={0};
22 int Time=0,n;
23 int ans[N]={0};
24 void tarjan(int u,int fa){
25     dfn[u]=lowcost[u]=++Time;
26     inst[u]=1;
27     st.push_back(u);
28     for(int i=0;i<G[u].size();i++){
29         int v=G[u][i];
30         if(!dfn[v]){
31             tarjan(v,u);
32             lowcost[u]=min(lowcost[u],lowcost[v]);
33         }
34         else if(v!=fa&&inst[v]==1){
35                 
36             int top=st.size();
37             ans[u]=ans[v]=1;
38             while(st[top-1]!=v){
39                 ans[st[top-1] ]=1;
40                 top--;
41             }
42             lowcost[u]=min(lowcost[u],dfn[v]);
43         }
44     }
45     if(dfn[u]==lowcost[u]){
46         int top=st.size();
47         while(st[top-1]!=u){
48             st.pop_back();
49             inst[st[top-1]];
50             top--;
51         }
52         inst[u]=0;
53         st.pop_back();
54     }
55 
56 }
57 
58 int main(){
59 
60     scanf("%d",&n);
61     int x,y;
62     for(int i=1;i<=n;i++){
63         scanf("%d%d",&x,&y);
64         G[x].push_back(y);
65         G[y].push_back(x);
66     }
67     for(int i=1;i<=n;i++){
68         if(!dfn[i])
69             tarjan(i,-1);
70         st.clear();
71     }
72     int flag=0;
73     int i,num;
74     for(i=1;!flag&&i<=n;i++){
75         if(ans[i]){
76             num=i;flag=1;
77         }
78     }
79     printf("%d",num);
80     for(;i<=n;i++){
81         if(ans[i])
82             printf(" %d",i);
83     }
84     cout<<endl;
85     return 0;
86 }
View Code

 

posted @ 2018-05-17 10:28  山枫叶纷飞  阅读(343)  评论(0编辑  收藏  举报