나무의 지름
1666 단어 나무.
DFS 를 여러 번 호출 해 야 하 는 상황 에서 여러 번 memset visited[N]는 많은 시간 을 소모 합 니 다(N 이 크기 때문에).변 수 를 추가 할 수 있 습 니 다 visitedid,매번 DFS,visitedid++,그리고 visited[N]==visited 판단id 면 돼.
#include <vector>;
using namespace std;
const static int N = 200003;
bool visited[N];
vector<int> curr_path;
vector<int> ans_path;
void dfs_helper(vector<vector<int>> &tree, int root, vector<int> &curr, vector<int> &ans) {
if (visited[root]) {
return;
}
visited[root] = true;
curr.push_back(root);
if (curr.size() > ans.size()) {
ans = curr; // vector copy, but most d times, d is the length of the diameter
}
int m = tree[root].size();
for (int i = 0; i < m; i++) {
dfs_helper(tree, tree[root][i], curr, ans);
}
curr.pop_back();
}
int dfs(vector<vector<int>> &tree, int root) {
curr_path.clear();
ans_path.clear();
memset(visited, false, sizeof(visited));
dfs_helper(tree, root, curr_path, ans_path);
return ans_path.back();
}
int main()
{
// int root = dfs(tree, 0);
// dfs(tree, root);
// then the ans_path is the shortest path in the tree
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
예제 1.15 UVALive-3902 트리의 검색컨베이어 도어 제목 대의: n대의 기계는 하나의 트리 네트워크로 연결되어 잎 노드는 클라이언트이고 다른 노드는 서버이다. 처음에는 한 대의 서버만 하나의 서비스를 제공했지만 k의 거리 내의 클라이언트만 덮어쓸 수 있...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.