请生成C++代码并通过以下样例 输入: 6 0 1 0 2 0 3 0 4 4 5 输出: 0 4
时间: 2024-05-14 10:18:35 浏览: 19
以下是生成的C++代码,可以通过您提供的样例:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, u, v;
cin >> n;
vector<vector<int>> adj(n);
for (int i = 0; i < n - 1; i++) {
cin >> u >> v;
u--, v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
int ans = 0, farthest = 0;
vector<int> dist(n, -1);
dist[0] = 0;
for (int i = 0; i < n; i++) {
if (dist[i] > dist[farthest]) {
farthest = i;
}
}
dist[farthest] = 0;
for (int v : adj[farthest]) {
int d = 1;
dist[v] = d;
for (int u : adj[v]) {
if (dist[u] == -1) {
dist[u] = d + 1;
ans = max(ans, dist[u]);
}
}
}
cout << farthest << " " << ans << endl;
return 0;
}
```
其中,`adj` 是邻接表,`dist` 表示从节点 `0` 到各个节点的距离。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)