๋ฌธ์
1967๋ฒ: ํธ๋ฆฌ์ ์ง๋ฆ
ํ์ผ์ ์ฒซ ๋ฒ์งธ ์ค์ ๋ ธ๋์ ๊ฐ์ n(1 ≤ n ≤ 10,000)์ด๋ค. ๋์งธ ์ค๋ถํฐ n-1๊ฐ์ ์ค์ ๊ฐ ๊ฐ์ ์ ๋ํ ์ ๋ณด๊ฐ ๋ค์ด์จ๋ค. ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ ์ธ ๊ฐ์ ์ ์๋ก ์ด๋ฃจ์ด์ ธ ์๋ค. ์ฒซ ๋ฒ์งธ ์ ์๋ ๊ฐ์ ์ด ์ฐ
www.acmicpc.net
์ฝ๋
#include <iostream>
#include <vector>
#include <memory.h>
using namespace std;
int max_len = 0;
int max_node;
bool visited[10001];
int ans;
vector<pair<int,int>>graph[10002];
void dfs(int node, int len){
visited[node] = 1;
if(max_len<len){
max_len = len;
max_node = node;
}
for(auto next: graph[node]){
if(!visited[next.first]){
visited[next.first] = 1;
dfs(next.first, next.second+len);
visited[next.first] = 0;
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int N; cin>>N;
for(int i=0; i<N-1; i++){
int a,b,c; cin>>a>>b>>c;
graph[a].push_back({b,c});
graph[b].push_back({a,c});
}
dfs(1, 0);
max_len = 0;
memset(visited,0,sizeof(visited));
dfs(max_node, 0);
ans += max_len;
cout<<ans;
}
ํ์ด
ํ์ด ์์ด๋์ด๋ ๋ฃจํธ ๋ ธ๋์์ ๊ธธ์ด๊ฐ ๊ฐ์ฅ ๊ธด ๋ ธ๋๋ฅผ ์ฐพ์ ๋ค, ๊ทธ ๋ ธ๋๋ก๋ถํฐ ๊ฐ์ฅ ๊ธด ๋ ธ๋๋ก ๊ฐ๋ ๊ธธ์ด๋ฅผ ๊ธฐ์ตํ๋ ๊ฒ์ ๋๋ค.
์ ์ฌ์ง์์๋ 1๋ฒ ๋ ธ๋์์ ์์ํ์ฌ 9๋ฒ๋ ธ๋๋ฅผ ์ฐพ์๋ค, 9๋ฒ๋ ธ๋๋ถํฐ 12๋ฒ ๋ ธ๋๊น์ง ์ด์ด์ง๋ ๊ฐ์ ์ ์ ๋ถ ๋ํ๋ ๊ฒ์ ๋๋ค.
- ๋จผ์ ๋ฃจํธ๋ ธ๋๋ ํญ์ 1๋ฒ์์ ๋ฌธ์ ์์ ๋ช ์๋์ด ์์ต๋๋ค.
- ๋ฃจํธ ๋ ธ๋๋ฅผ ๊ธฐ์ ์ผ๋ก ์ต๋ ๊ฐ์ ๊ธธ์ด๋ฅผ ๊ฐฑ์ ํด๊ฐ๋ฉฐ ๋ฆฌํ ๋ ธ๋๋ฅผ ์ฐพ์ต๋๋ค.
- ๊ทธ ๋ฆฌํ๋ ธ๋๋ก๋ถํฐ ๊ฐ์ฅ ๊ธด ๊ฐ์ ์ ๊ฐ์ง ๋ฆฌํ ๋ ธ๋๊ฐ ๋์ฌ ๋๊น์ง ๊ฐ์ ์ ๊ธธ์ด๋ฅผ ๋ํฉ๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค,c++] 20365๋ฒ - ๋ธ๋ก๊ทธ2 (0) | 2022.07.24 |
---|---|
[๋ฐฑ์ค,c++] 12933๋ฒ - ์ค๋ฆฌ (0) | 2022.07.19 |
[๋ฐฑ์ค,c++] 1343๋ฒ - ํด๋ฆฌ์ค๋ฏธ๋ ธ (0) | 2022.07.14 |
[๋ฐฑ์ค,c++] 3584๋ฒ - ๊ฐ์ฅ ๊ฐ๊น์ด ๊ณตํต ์กฐ์ (0) | 2022.07.11 |
[๋ฐฑ์ค,c++] 14675๋ฒ - ๋จ์ ์ ๊ณผ ๋จ์ ์ (0) | 2022.06.30 |
[๋ฐฑ์ค,c++] 6416๋ฒ - ํธ๋ฆฌ์ธ๊ฐ? (0) | 2022.06.30 |
๋๊ธ