๋ฌธ์
20924๋ฒ: ํธ๋ฆฌ์ ๊ธฐ๋ฅ๊ณผ ๊ฐ์ง
์ฒซ ๋ฒ์งธ ์ค์๋ ๋ ธ๋์ ๊ฐ์ $N$($1 \le N \le 200\,000$)๊ณผ ๋ฃจํธ ๋ ธ๋์ ๋ฒํธ $R$($1 \le R \le N$)์ด ์ฃผ์ด์ง๋ค. ์ดํ $N-1$๊ฐ์ ์ค์ ์ธ ๊ฐ์ ์ ์ $a$, $b$, $d$($1 \le a, b \le N$, $ a \ne b$)๊ฐ ์ฃผ์ด์ง๋ค. ์ด๋ $a$๋ฒ
www.acmicpc.net
์ฝ๋
#include <iostream>
#include <vector>
#include <memory.h>
using namespace std;
vector<pair<int,int>>tree[200001];
bool visited[200001];
int trunk_len, start_branch, branch_len, end_branch;
void find_trunk(int node, int len){
visited[node] = true;
trunk_len = len;
start_branch = node;
if(tree[node].size()>2) return;
for(auto next: tree[node]){
if(!visited[next.first]){
visited[next.first] = true;
find_trunk(next.first,len+next.second);
}
}
}
void find_branch(int node, int len){
visited[node] = true;
if(len>branch_len){
end_branch = node;
branch_len = len;
}
for(auto next: tree[node]){
if(!visited[next.first]){
visited[next.first] = true;
find_branch(next.first,len+next.second);
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int N, R; cin>>N>>R;
for(int i=0; i<N-1; i++){
int a, b, c; cin>>a>>b>>c;
tree[a].push_back({b,c});
tree[b].push_back({a,c});
}
if(tree[R].size()>=2){
find_trunk(R, 0);
trunk_len = 0;
memset(visited, 0, sizeof(visited));
find_branch(R, 0);
}
else{
find_trunk(R, 0);
find_branch(start_branch, 0);
}
cout<<trunk_len<<' '<<branch_len;
}
ํ์ด
๋ฌธ์ ์ ์กฐ๊ฑด ๊ทธ๋๋ก dfs๋ฅผ ์ด์ฉํ๋ฉด ์ฝ๊ฒ ํด๊ฒฐํ ์ ์๋ ๋ฌธ์ ์ ๋๋ค.
- ๋ฃจํธ ๋ ธ๋๋ ๋ฌธ์ ์์ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๊ธฐ ๋๋ฌธ์ ๋ฃจํธ ๋ ธ๋๋ถํฐ dfs๋ฅผ ์ถ๋ฐํด์ ๊ธฐ๋ฅ๊น์ง ๊ธธ์ด๋ฅผ ๊ตฌํด์ฃผ๊ณ , ๊ธฐ๋ฅ์ด ๋๋๋ ์ง์ ๋ํ ๊ธฐ๋กํฉ๋๋ค.
- ๊ทธ๋ค์ ๊ธฐ๋ฅ์ด ๋๋๋ ์ง์ ์์ ๊ฐ์ฅ ๊ธด ๋ฆฌํ ๋ ธ๋๊น์ง์ ๊ธธ์ด๋ฅผ ๊ตฌํ๋ฉด ๋ฉ๋๋ค.
์ฃ์ง ์ผ์ด์ค
3 1
1 2 5
1 3 5
๋ต : 0 5
์์ ๊ฐ์ด ๊ธฐ๋ฅ์ด ์๊ณ , ๊ฐ์ง๊ณ 2๊ฐ์ธ ๊ฒฝ์ฐ๋ฅผ ์ ์ฒ๋ฆฌํด์ฃผ์ด์ผ ํฉ๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค,c++] 2138๋ฒ - ์ ๊ตฌ์ ์ค์์น (0) | 2022.07.27 |
---|---|
[๋ฐฑ์ค,c++] 1167๋ฒ - ํธ๋ฆฌ์ ์ง๋ฆ (0) | 2022.07.26 |
[๋ฐฑ์ค,c++] 9489๋ฒ - ์ฌ์ด (0) | 2022.07.26 |
[๋ฐฑ์ค,c++] 20365๋ฒ - ๋ธ๋ก๊ทธ2 (0) | 2022.07.24 |
[๋ฐฑ์ค,c++] 12933๋ฒ - ์ค๋ฆฌ (0) | 2022.07.19 |
[๋ฐฑ์ค,c++] 1343๋ฒ - ํด๋ฆฌ์ค๋ฏธ๋ ธ (0) | 2022.07.14 |
๋๊ธ