846. The center of gravity of the tree+DFS

Given a tree, the tree contains n nodes (numbered 1∼n) and n−1 undirected edges.

Please find the center of gravity of the tree and output the maximum number of points in the remaining connected blocks after the center of gravity is removed.

Definition of the center of gravity: The center of gravity refers to a node in the tree. If the maximum number of points in the remaining connected blocks is the smallest after this point is deleted, then this node is called the center of gravity of the tree.

Input format
The first line contains the integer n, which represents the number of nodes in the tree.

The next n−1 lines, each containing two integers a and b, indicate that there is an edge between point a and point b.

Output Format
Output an integer m, which represents the maximum number of points in the remaining connected blocks after the center of gravity is removed.

Data range
1≤n≤105Input
samples
9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6Output
samples:
4

#include<bits/stdc++.h>
using namespace std;
const int N = 100010, M = N * 2;
//模拟哈希
int h[N], e[M], ne[M], idx;
int n;
int ans = N;
bool vis[N];

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

int dfs(int u)
{
    
    
    vis[u] = true;
    
    int sum = 1, res = 0;
    for(int i=h[u]; i!=-1; i= ne[i]) {
    
    
        int j = e[i];
        
        if(!vis[j]) {
    
    
            //返回的为该数的子结点个数
            int s = dfs(j);
            res = max(res, s);
            sum += s;
        }
    }
    res = max(res, n - sum);
    ans = min(res, ans);
    return sum;
}

int main()
{
    
    
    cin >> n;
    
    memset(h, -1, sizeof h);
    
    for(int i=0; i<n-1; i++) {
    
    
        int a, b;
        cin >> a >> b;
        add(a, b);
        add(b, a);
    }
    
    dfs(1);
    
    cout << ans << endl;
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324142724&siteId=291194637