알고리즘 공부

백준 알고리즘 수업 -깊이 우선 탐색3

컴퓨터과학 2023. 7. 30. 20:06

https://www.acmicpc.net/problem/24481

 

24481번: 알고리즘 수업 - 깊이 우선 탐색 3

깊이 우선 탐색 트리는 1, 2, 3, 4번 노드로 구성된다. 1번 노드가 루트이다. 1번 노드의 자식은 2번 노드이다. 2번 노드의 자식은 3번 노드이다. 3번 노드의 자식은 4번 노드이다. 5번 노드는 1번 노드

www.acmicpc.net

흠 이번 문제는 뭔가 같은 깊이에 있는얘들 케이스를 출력해주는 문제?

#include <iostream>
#include <vector>
#include <queue>
#include<string>
#include<algorithm>
#include<cmath>
#include<unordered_map>
#include<map>
#include<stack>
using namespace std;

struct Point {
	int s, e, t, cnt, power;
	char c;
};

void Prints(vector<vector<int>>maps, int n, int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

void Prints(vector<vector<bool>>maps, int n, int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j];
		}
		cout << endl;
	}
	cout << endl;
}
void Prints(vector<vector<char>>maps, int n, int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j];
		}
		cout << endl;
	}
	cout << endl;
}
void Prints(vector<vector<vector<char>>>maps, int n, int m, int k) {
	for (int t = 0; t < k; t++) {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cout << maps[t][i][j];
			}
			cout << endl;
		}
		cout << endl;
	}
	cout << endl;
}

void Prints(vector<vector<vector<bool>>>maps, int n, int m, int k) {
	for (int t = 0; t < k; t++) {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cout << maps[t][i][j];
			}
			cout << endl;
		}
		cout << endl;
	}
	cout << endl;
}
void Prints(string str, int n) {
	for (int i = 0; i < n; i++) {
		cout << str[i] << ",";
	}
	cout << endl;
}

struct Data {
	unsigned long long index;
	unsigned long long value;
};

bool compares(const Point &a, const Point &b) {
	if (a.s == b.s) {
		return a.e < b.e;
	}
	return a.s < b.s;
	
}

int n, m, r;
vector<bool>bVisited;
vector<vector<int>>glists;
map<int, int>anw;
int gCount = 0;
void dfs(int k,int cnt) {
	bVisited[k - 1] = true;
	
	for (int i = 0; i < glists[k].size(); i++) {
		if (bVisited[glists[k][i]-1] == false) {
		//	cout << glists[k][i]<<",";
			//1
			anw[glists[k][i]] = cnt;
			
			dfs(glists[k][i], cnt +1);
		}
		//cout <<endl;
	}
}
int main() {
	cin >> n >> m >> r;
	vector<vector<int>>lists(n+1);
	/*
	0
	1
	2
	..n
	*/
	vector<Point>nodes;
	for (int i = 0; i < m; i++) {
		int s,e;
		cin >> s >> e;
		Point p;
		p.s = s;
		p.e = e;
		nodes.push_back(p);
	}

	for (int i = 0; i < n; i++) {
		bVisited.push_back(false); //0~n-1
		anw[i+1] = -1;//1~n
	}
	sort(nodes.begin(), nodes.end(),compares);
	for (int i = 0; i < m; i++) {
		lists[nodes[i].s].push_back(nodes[i].e);
		lists[nodes[i].e].push_back(nodes[i].s);
	}
	
	glists = lists;
	anw[r] = gCount;//0
	dfs(r, gCount +1);
	for (auto iter = anw.begin(); iter != anw.end(); iter++) {
		cout << iter->second<<'\n';
	}
	return 0;
}