1021 Deepest Root (25 分)c++實現【已AC】

#include<iostream>
#include<set>
#include<vector>
#include<cstdio>
using namespace std;
const int maxn = 10005;
set<int> G[maxn];
bool marked[maxn]{ 0 };
int component = 0, depth = 0, max_depth = 0, cur_root;
set<int> deepest, deepest1;

void dfs_s(int v, set<int> &deepest) {
   marked[v] = true;
   bool flag = false;
   depth++;

   if (depth > max_depth) {
   	deepest.clear();
   	deepest.insert(v);
   	max_depth = depth;
   }
   else if (depth == max_depth)
   	deepest.insert(v);

   for (auto w : G[v]) {
   	if (!marked[w]) {
   		dfs_s(w, deepest);
   		flag = true;
   	}
   }
   depth--;
}
int main() {
   int n;
   scanf("%d", &n);
   int v, w;
   for (int i = 0; i < n - 1; i++) {
   	scanf("%d%d", &v, &w);
   	G[v].insert(w);
   	G[w].insert(v);
   }
   for (int i = 1; i <= n; i++) {
   	if (!marked[i]) {
   		component++;
   		dfs_s(i, deepest);
   	}
   }
   if (component > 1) printf("Error: %d components", component);//Error: K components
   else {
   	for (auto i : deepest) deepest1.insert(i);
   	fill(marked, marked + n + 1, false);
   	depth = 0;max_depth = 0;
   	dfs_s(*(deepest.begin()), deepest1);
   	for (auto i : deepest) deepest1.insert(i);
   	for (auto p : deepest1) printf("%d\n", p);
   }
   system("pause");
   return 0;
}

測試數據集

// 1應當返回1
1

5
1 2
1 3
1 4
1 5

5
1 2
2 3
3 4
4 5

6
1 2
1 3
1 4
2 5
4 6

// 和測試點4,5相關, 第一輪搜索的多個最深點,兩兩之間不一定最深,但是在第二輪搜索中是可以相互替代的, 所以他們都會出現在最終的點集中
6
1 2
1 3
3 4
4 5
4 6
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章