๋ฌธ์
์ฝ๋
#include <string>
#include <vector>
#include <memory.h>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int>graph[20001], dists;
bool visited[20001];
int dist[20001];
int max_dist = -1;
void bfs(int start){
queue<int>q;
q.push(start);
visited[start] = 1;
while(!q.empty()){
int x = q.front();
q.pop();
for(int next: graph[x]){
if(!visited[next]){
dist[next] = dist[x] + 1;
max_dist = max(dist[next] ,max_dist);
visited[next] = 1;
q.push(next);
}
}
}
}
int solution(int n, vector<vector<int>> edge) {
int answer = 0;
for(int i=0; i<edge.size(); i++){
int a = edge[i][0];
int b = edge[i][1];
graph[a].push_back(b);
graph[b].push_back(a);
}
bfs(1);
for(int i:dist){
if(i==max_dist) answer++;
}
return answer;
}
int main(){
cout<<solution(6, {{3, 6}, {4, 3}, {3, 2}, {1, 3}, {1, 2}, {2, 4}, {5, 2}});
}
ํ์ด
์ ์ผ ์ฒ์์ ํ๋ก์ด๋-์์ฌ๋ก ํด๊ฒฐ์ ํ๋ ค๊ณ ํ์ผ๋, ๋ ธ๋์ ๊ฐ์๊ฐ 20,000๊น์ง ๋ค์ด์ค๊ธฐ์ O(N^3)์ธ ํ๋ก์ด๋๋ก๋ ํด๊ฒฐํ ์๊ฐ ์์ด dfs๋ก ํด๊ฒฐ์ ํ๋ ค๊ณ ํ์ต๋๋ค. 1๋ฒ์ ์ ์ธํ ๋ชจ๋ ๊ฐ ๋ ธ๋์์ ์ถ๋ฐํ์ฌ 1๋ฒ ์ด ๋ ๋๊น์ง ํ์ํ์ฌ ์๋์ ๊ฐ์ด ๊ตฌํํ์ต๋๋ค.
#include <string>
#include <vector>
#include <memory.h>
#include <algorithm>
using namespace std;
vector<int>graph[20001];
bool visited[20001];
vector<int>dists;
int temp_dist = 1e9, min_dist=1e9;
void dfs(int x, int depth){
visited[x] = 1;
if(x == 1){
temp_dist = min(temp_dist,depth);
return;
}
for(int i:graph[x]){
if(visited[i]) continue;
visited[i] = 1;
dfs(i,depth+1);
visited[i] = 0;
}
}
int solution(int n, vector<vector<int>> edge) {
int answer = 0;
for(int i=0; i<edge.size(); i++){
int a = edge[i][0];
int b = edge[i][1];
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i=2; i<=n; i++){
dfs(i,1);
min_dist = min(min_dist, temp_dist);
dists.push_back(temp_dist);
temp_dist = 1e9;
memset(visited,0,sizeof(visited));
}
sort(dists.begin(),dists.end(),greater<>());
int max_dist = dists.front();
for(int i:dists){
if(i==max_dist) answer++;
}
return answer;
}
ํ์ง๋ง 1, 2, 3๋ฒ์ ํ ์คํธ์ผ์ด์ค ๋นผ๊ณ ๋ ์ ๋ถ ์๊ฐ ์ด๊ณผ๊ฐ ๋ด๋๋ฐ, ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ๋ ๊ฒฝ์ฐ ๊ฐ์ค์น๊ฐ 0๊ณผ 1๋ฐ์ ์๊ธฐ์ BFS๋ก ํธ๋ ๊ฒ ํจ์จ์ ์ด๋ผ๋ ๊ฒ์ ์์ ์ ๋ฐฐ์์ ์ธ์งํ๊ณ ์์์ง๋ง dfs์ ์ต์ํด์ ธ์ ํ์๋๋ ๋ญํจ๋ฅผ ๋ดค์ต๋๋ค.
๊ทธ๋ํ ์ด๋ก ์๊ณ ๋ฆฌ์ฆ์ ์ข ๋ ๋ง์ด ํ์ด๋ด์ผ ํ ๊ฒ ๊ฐ์ต๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > ํ๋ก๊ทธ๋๋จธ์ค(Programmers)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL] ํ๋ก๊ทธ๋๋จธ์ค - SQL ๊ณ ๋์ Kit (0) | 2022.05.28 |
---|---|
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์ฌํ๊ฒฝ๋ก(Level 3) (0) | 2022.05.27 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - [3์ฐจ] ํ์ผ๋ช ์ ๋ ฌ(Level 2) (0) | 2022.05.04 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์ ํ์ ์๊ฐ ์ด๋(Level 2) (0) | 2022.05.01 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ์ด์ง ๋ณํ ๋ฐ๋ณตํ๊ธฐ(Level 2) (0) | 2022.04.26 |
[c++] ํ๋ก๊ทธ๋๋จธ์ค - ๊ตฌ๋ช ๋ณดํธ(Level 2) (0) | 2022.04.25 |
๋๊ธ