Questions previous questions found ring dfs solution (no timeout)

Resource constraints
Time limit: 1.0s memory limit: 256.0MB
description of the problem
  Xiaoming laboratories have N computers, numbered 1 ~ N. Originally had connected N-1 th data link between the computer N, form a tree network exactly. On tree network, between any two computers are connected with a unique path.

But in a recent maintain the network, the administrator of a malfunction between two computers so that adds a data link, so that a loop network. Since the computer on the loop between any two is no longer only one path, so that data transmission occurred on these computers BUG.

In order to restore normal transmission. Xiao Ming need to find all the computers on the loop, can you help him?
Input format
  The first line contains an integer N.
  The following N lines of two integers a and b, is connected to a data link expressed between a and b.

For 30% of the data, 1 <= N <= 1000
  data to 100 percent, 1 <= N <= 100000 , 1 <= a, b <= N

Enter the legal guarantee.
Output format
  output number of computers on the loop in order from small to large, separated by an intermediate space.
Sample input
. 5
. 1 2
. 3. 1
2. 4
2. 5
. 5. 3
sample output
1235
/ ---------------------------- -------------------------------------------------- ------------------------- /

Reference blog Click here

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<vector> 
#include<cstring>
using namespace std;
const int maxn = 100005; 
struct node{
	int end;//终点的序号
	int vis;//是否被访问过
};
int road[maxn];//记录经过的路径
vector<node> roads[maxn];//定义一个结构体数组记录节点之间的联系,有很多条联系所以road加了s。。。以下代码注意区分
int vis[maxn];//记录路径是否经过该节点,经过一次后则为非原始定义值,当第二次到达该节点时,值为非原始定义值,就是环路产生
int huan[maxn];//最终环的路径
int r;//数组road【】的下标
int h;//数组huan【】的下标
void dfs(int x){
	if(vis[x] != -1){//第二次到达x节点,代表环路形成,记录最终环路径,结束dfs
		for(int j = vis[x];j < r;j++){
			huan[h++] = road[j];
		}
		return ;
	}
	vis[x] = r;
	road[r] = x;
	r++;
	for(int i=0;i<roads[x].size();i++){
		if(roads[x][i].vis!=true){
			roads[x][i].vis = true;
			int z = roads[x][i].end;
			for(int j=0;j<roads[z].size();j++){//切断两节点之间的联系,防止返回造成环路假象
				if(roads[z][j].end == x){
					roads[z][j].vis = true;
					break;
				}
			}
			dfs(z);
			r--;
		}
	}
	return ;
}

int main(){
	int a,b,n;
	cin>>n;
	for(int i=0;i<n;i++){//录入各个节点的链接
		cin>>a>>b;
		node temp;
		temp.end = b;temp.vis = false;
		roads[a].push_back(temp);
		temp.end = a;
		roads[b].push_back(temp);
	}
	memset(vis,-1,sizeof(vis));//将vis原始值定义为-1
	dfs(1);
	sort(huan,huan+h);//排序
	for(int i=0;i<h;i++)//输出环路
		cout<<huan[i]<<" ";
	return 0;
}
发布了16 篇原创文章 · 获赞 15 · 访问量 1542

Guess you like

Origin blog.csdn.net/qq_43320728/article/details/104702732