LeetCode 5538. Count the maximum distance between cities in the subtree (enumerate all possible + maximum diameter of the graph)

Article Directory

1. Title

Give you n cities, numbered from 1 to n. While giving you an array of size edges n-1 which edges[i] = [ui, vi]represents the city there is a two-way side between ui and vi.
The title guarantees that there is only one path between any cities. In other words, all cities form a tree.

A subtree is a subset of cities, and any city in the subset can be reached through other cities and edges in the subset.
The condition for two subtrees to be considered different is that at least one city exists in one of the subtrees but does not exist in the other subtree.

For d from 1 to n-1, you find the city between the maximum distance is exactly the number of all the sub-tree d.

Please return an array of size n-1, where the d-th element (subscript starting from 1) is the number of subtrees whose maximum distance between cities is exactly equal to d.

Please note that the distance between two cities is defined as the number of edges that need to pass between them.

Example 1:

输入:n = 4, edges = [[1,2],[2,3],[2,4]]
输出:[3,4,0]
解释:
子树 {
    
    1,2}, {
    
    2,3}{
    
    2,4} 最大距离都是 1 。
子树 {
    
    1,2,3}, {
    
    1,2,4}, {
    
    2,3,4}{
    
    1,2,3,4} 最大距离都为 2 。
不存在城市间最大距离为 3 的子树。

示例 2:
输入:n = 2, edges = [[1,2]]
输出:[1]

示例 3:
输入:n = 3, edges = [[1,2],[2,3]]
输出:[2,1]
 
提示:
2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
题目保证 (ui, vi) 所表示的边互不相同。

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/count-subtrees-with-max-distance-between-cities The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. Problem solving

Similar topic: LeetCode 1245. The diameter of the tree (the conclusion of the maximum diameter of the figure)

  • Backtrack first to generate all possible subsets
  • For each subset, determine whether all points are connected
  • Then calculate the maximum diameter of the connection diagram
  1. Choose any point A to start bfs, record the last point B traversed
  2. Start the bfs traversal from B, and finally reach the point C, the distance of BC is the maximum diameter
class Solution {
    
    
    vector<int> ans;
    vector<vector<int>> g;//图
    vector<int> sub;//子节点集
    int N;
public:
    vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {
    
    
        N = n;
        sub = vector<int> (n, 0);
        ans = vector<int> (n-1, 0);
        g.resize(n);
        for(auto& e : edges)
        {
    
    
            g[e[0]-1].push_back(e[1]-1);
            g[e[1]-1].push_back(e[0]-1);
        }
        dfs(0);
        return ans;
    }
    void dfs(int i)
    {
    
    
        if(i == N)
        {
    
    
            int d = calculateD();
            if(d != -1)
                ans[d-1]++;
            return;
        }
        dfs(i+1);//当前点不选
        sub[i] = 1;//标记节点选中了
        dfs(i+1);//当前点选
        sub[i] = 0;//回溯
    }
    int calculateD()//判断联通,以及最大直径
    {
    
    
        int start = -1;
        for(int i = 0; i < N && start == -1; ++i)
            if(sub[i] == 1)
                start = i;
        int last = bfs(start, true);//以任意一点开始bfs
        if(last == -1)//图不连通,返回
            return -1;
        return bfs(last, false);//以last点开始bfs求最大直径
    }
    int bfs(int id, bool option)
    {
    
    
        int count = 0, total = accumulate(sub.begin(),sub.end(),0);
        if(total <= 1)
            return -1;// 少于2个点,不满足题意
        int last, size, step = 0;
        vector<int> unvis(sub);
        queue<int> q;
        q.push(id);
        unvis[id] = 0;
        while(!q.empty())
        {
    
    
            size = q.size();
            while(size--)
            {
    
    
                last = id = q.front();
                q.pop();
                count++;
                for(int nt : g[id])
                {
    
    
                    if(unvis[nt])
                    {
    
    
                        unvis[nt] = 0;
                        q.push(nt);
                    }
                }
            }
            step++;
        }
        if(option == true)
        {
    
    
            if(count != total)
                return -1;//不连通
            return last;//最后一个点
        }
        else
        {
    
    
            return step-1;
        }
    }
};

1140 ms 399.6 MB


My CSDN blog address https://michael.blog.csdn.net/

Long press or scan the code to follow my official account (Michael Amin), cheer together, learn and progress together!
Michael Amin

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/109014936