牛客——百鸟国(并查集和深度优先搜索)

链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
 

 凤凰于飞,翙翙其羽,亦集爰止。

                                        ——《诗经·卷阿》

    传说,凤凰是百鸟之王。有一天,凤凰要召开百鸟大会,百鸟国是一个由n个节点组成的树,每个节点有一只鸟,开会的节点定在1号节点。每只鸟可以花费1s通过一条边,由于每根树枝(边)的载重有限,只允许一只鸟同时通过。作为会议的策划师,HtBest想知道百鸟国的所有鸟在1点集合最少需要多少秒。
 

输入描述:

第一行有一个正整数n,表示百鸟国节点个数。
接下来n-1行,第i行两个正整数ai,bi用空格隔开,表示树上节点ai,bi之间有一条边。

输出描述:

第一行一个整数,表示集合最少需要的时间。

牛客——百鸟国(并查集和深度优先搜索)_第1张图片

#include 
#include 
using namespace std;

int find(vector& p, int x) {
    if (p[x] != x) {
        p[x] = find(p, p[x]);
    }
    return p[x];
}

int main() {
    int n;
    cin >> n;
    
    vector p(n + 1);
    vector siz(n + 1, 1);
    
    for (int i = 1; i <= n; i++) {
        p[i] = i;
    }
    
    while (n--) {
        int a, b;
        cin >> a >> b;
        
        int rootA = find(p, a);
        int rootB = find(p, b);
        
        if (rootA != rootB && rootA != 1 && rootB != 1) {
            siz[rootB] += siz[rootA];
            p[rootA] = rootB;
        }
    }
    
    int res = 0;
    for (auto s : siz) {
        res = max(res, s);
    }
    
    cout << res << endl;
    
    return 0;
}
#include 
#include 
using namespace std;

vector> adj;
vector visited;

int dfs(int pre) {
    int cnt = 1;
    for (auto u : adj[pre]) {
        if (!visited[u]) {
            visited[u] = true;
            cnt += dfs(u);
            visited[u] = false;
        }
    }
    return cnt;
}

int main() {
    int n;
    cin >> n;

    adj.resize(n + 5);
    visited.resize(n + 1);

    for (int i = 0; i < n - 1; ++i) {
        int x, y;
        cin >> x >> y;

        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    int ans = 0;
    visited[1] = true;
    for (auto ai : adj[1]) {
        visited[ai] = true;
        ans = max(ans, dfs(ai));
        visited[ai] = false;
    }

    cout << ans << endl;

    return 0;
}
#include 
#include 
#include 
using namespace std;

const int N = 1e6 + 10;
const int M = 2 * N;
typedef long long LL;

int e[M], ne[M], h[N], idx;
int dep[N], sz[N];
int ans[N];

void add(int a, int b) {
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}

void dfs(int u, int fa) {
    sz[u] = 1;
    for (int i = h[u]; i != -1; i = ne[i]) {
        int j = e[i];
        if (j == fa) {
            continue;
        }
        dfs(j, u);
        sz[u] += sz[j];
        ans[u] = max(ans[u], sz[j]);
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    memset(h, -1, sizeof h);
    
    int n;
    cin >> n;
    
    for (int i = 1; i < n; i++) {
        int a, b;
        cin >> a >> b;
        add(a, b);
        add(b, a);
    }
    
    dfs(1, 0);
    
    cout << ans[1] << endl;
    
    return 0;
}

 

你可能感兴趣的:(算法,数据结构,并查集,深度优先搜索)