728x90
๋ฌธ์
https://www.acmicpc.net/problem/16947
ํ์ด ์ฌ์ง ์ฐธ๊ณ
์ฝ๋
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAX = 3001;
int n;//๋ฌธ์ ์์ ์ฃผ์ด์ง ์ญ์ ๊ฐ์
vector<int> stations[MAX];//๋ฌธ์ ์์ ์ฃผ์ด์ง ์ญ ์ ๋ณด
bool visited[MAX];//BFS/DFS ํ์์ ์ํ ๋ฐฉ๋ฌธ์ฒดํฌ ๋ฐฐ์ด
bool cycle_stations[MAX];//์ํ์ญ ์ฌ๋ถ๋ฅผ ์ ์ฅํ ๋ฐฐ์ด(true or false)
void Input();
void SearchCycle(int start_station, int current_station, int searchNum);//์ฌ์ดํด ์ฌ๋ถ ํ์(์์์ญ, ํ์์ค์ธ ํ์ฌ์ญ, ํ์๊น์ด)
int CalculateDistance(int start_station);//์ํ์ญ๊น์ง์ ๊ฑฐ๋ฆฌ ๊ตฌํ๊ธฐ
int main() {
//1. ์ญ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
Input();
//2. ์ํ์ญ ํ์
for (int i = 1; i <= n; i++) {
SearchCycle(i,i,0);
memset(visited, false, sizeof(visited));
}
//3. ์ํ์ญ๊ณผ์ ๊ฑฐ๋ฆฌ ํ์ ๋ฐ ์ถ๋ ฅ
for (int i = 1; i <= n; i++) {
cout << CalculateDistance(i) << " ";
}
return 0;
}
void Input() {
cin >> n;
int station1, station2;
for (int i = 0; i < n; i++) {
cin >> station1 >> station2;
stations[station1].push_back(station2);
stations[station2].push_back(station1);
}
}
void SearchCycle(int start_station, int current_station, int searchNum) {//DFS
visited[current_station] = true;
for (int i = 0; i < stations[current_station].size(); i++) {
int next_station = stations[current_station][i];
if (!visited[next_station]) {
SearchCycle(start_station, next_station, searchNum + 1);
}
else {//๋ฐฉ๋ฌธํ๋ ์ญ์ด๊ณ ํ์ ๊น์ด๊ฐ 2์ด์์ด๋ฉด ์ํ์ญ์ด๋ผ๊ณ ํ๋จ
if (next_station == start_station && searchNum >= 2) {
cycle_stations[start_station] = true;
}
}
if (cycle_stations[start_station]) return;
}
}
int CalculateDistance(int start_station) {//BFS
queue<pair<int,int>> q;
memset(visited, false, sizeof(visited));
visited[start_station] = true;
q.push(make_pair(start_station,0));
while (!q.empty()) {
int current_station = q.front().first;
int current_distance = q.front().second;
q.pop();
if (cycle_stations[current_station]) { return current_distance; }
for (int i = 0; i < stations[current_station].size(); i++) {
int next_station = stations[current_station][i];
if (!visited[next_station]) {
visited[next_station] = true;
q.push(make_pair(next_station, current_distance + 1));
}
}
}
}
728x90
'๐ Coding Test Study > Algorithm Problem' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++][Baekjoon] 14503๋ฒ ๋ก๋ด ์ฒญ์๊ธฐ (0) | 2021.08.22 |
---|---|
[C++][Baekjoon][DP] 1309๋ฒ ๋๋ฌผ์ (0) | 2021.08.22 |
[C++][BAEKJOON][Dijkstra Alg] 1261๋ฒ ์๊ณ ์คํ (0) | 2021.08.22 |
[C++][ํ๋ก๊ทธ๋๋จธ์ค][2021 ์นด์นด์ค ์ฑ์ฉ์ฐ๊ณํ ์ธํด์ญ] ์ซ์ ๋ฌธ์์ด๊ณผ ์๋จ์ด (0) | 2021.08.22 |
[C++][ํ๋ก๊ทธ๋๋จธ์ค] 2021 ์นด์นด์ค ์ธํด์ญ ๋ฌธ์ , ๊ฑฐ๋ฆฌ๋๊ธฐ ํ์ธํ๊ธฐ (0) | 2021.08.17 |