天梯赛_L2-031 深入虎穴(DFS)

团体程序设计天梯赛

L2-031 深入虎穴

dfs/bfs,我采用的是dfs,题目中没有给出根节点,需要自己判断。在dfs的过程中记录最深点,之后输出即可。

#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > tree;
vector<bool> isRoot;
int maxNode, maxValue = 0;
void dfs(int node, int depth){
    if(depth > maxValue){
        maxNode = node;
        maxValue = depth;
    }
    for(int i = 0; i <= (int)tree[node].size() - 1; i++)
        dfs(tree[node][i], depth + 1);
}
int main(){
    int n;
    cin >> n;
    tree.resize(n);
    isRoot.resize(n, 1);
    for(int i = 0; i <= n - 1; i++){
        int k;
        cin >> k;
        for(int j = 0; j <= k - 1; j++){
            int temp;
            cin >> temp;
            isRoot[temp - 1] = 0;
            tree[i].push_back(temp - 1);
        }
    }
    for(int i = 0; i <= n - 1; i++){
        if(isRoot[i]) dfs(i, 1);
    }
    cout << maxNode + 1 << endl;
    return 0;
}