美文网首页
5538. 统计子树中城市之间最大距离

5538. 统计子树中城市之间最大距离

作者: 来到了没有知识的荒原 | 来源:发表于2020-10-12 16:32 被阅读0次

5538. 统计子树中城市之间最大距离

状态压缩子树选点
判断子树是否合法
两次bfs求直径

const int N=20;
int dist[N];
queue<int>q;
vector<int> g[N];

void bfs(int root,int s){
    memset(dist,-1,sizeof dist);
    while(q.size())q.pop();
    dist[root]=0;
    q.push(root);
    while(q.size()){
        int now=q.front();q.pop();
        for(auto v:g[now]){
            if (((s >> v) & 1) == 0) continue;
            if(dist[v]==-1){
                dist[v]=dist[now]+1;
                q.push(v);
            }
        }
    }
}

class Solution {
public:
    vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {
        for(int i=0;i<=n;i++)g[i]=vector<int>();
        vector<int>res(n-1,0);
        
        for(auto v:edges){
            int a=v[0]-1,b=v[1]-1;
            g[a].push_back(b);
            g[b].push_back(a);
        }
        
        int lim=1<<n;
        for(int s=1;s<lim;s++){
            // 遍历所有状态
            int total=0,root=-1;
            for(int i=0;i<n;i++){
                if((s>>i)&1){
                    total++;
                    if(root=-1)root=i;
                }
            }  
            if(total<=1)continue; // 要求是城市对,所以子树中要含2个及以上城市
            
            int mx=root,cnt=0;
            bfs(root,s); // 第一次bfs找到最远点
            
            for(int i=0;i<n;i++){
                if(dist[i]>=0){
                    cnt++;
                    if(dist[i]>dist[mx])mx=i;
                }
            }
            if(cnt!=total)continue; // 判断子树是否成立
            
            bfs(mx,s);  // 从最远点开始第二次bfs找到真实最远点
            
            for(int i=0;i<n;i++){
                if(dist[i]>dist[mx])mx=i;
            }
            
            res[dist[mx]-1]++;
        }
        return res;
    }
};
```![无标题.png](https://img.haomeiwen.com/i11440646/641c6c825509cd6e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

相关文章

  • 5538. 统计子树中城市之间最大距离

    5538. 统计子树中城市之间最大距离[https://leetcode-cn.com/problems/coun...

  • 二叉树内两个节点的最长距离

    二叉树内两个节点的最长距离 二叉树中两个节点的最长距离可能有三种情况: 1.左子树的最大深度+右子树的最大深度为二...

  • 城市之间的距离

    两座城市之间的距离到底有多远呢? 应该是不远的吧,你看,有了汽车,火车,动车,高铁和飞机等等的交通工具,花...

  • 获得树的深度(深度优先遍历)(递归)

    思想 先获得左右子树的最大深度 比较左右子树的最大深度 返回当前子树最大深度+1的值 代码 经典 leetcode...

  • 二叉树 - 最大距离

    参考二叉树的最大距离 求二叉树的深度代码很简洁,如下: 我们要求的二叉树的最大距离,肯定是某个节点左子树的高度加上...

  • 爱和距离

    人与人之间最大的差别和距离,是思想的差别和距离;爱可以超越差别和距离。

  • 成都户外:我终于明白,一生一定要去次稻城亚丁的意义了

    你和我之间的距离仿佛是一个城市的距离 你和我之间的距离却是差一次旅行的距离 OUR STORY ( Start w...

  • LeetCode #250 Count Univalue Sub

    250 Count Univalue Subtrees 统计同值子树 Description: Given the...

  • 刺猬法则

    刺猬法则是指人际交往中“心理距离效应”,即人与人之间应当保持适当的距离,只有这样才能最大限度地感受彼此的美...

  • 树链剖分

    适用题目特征 修改树上两点之间的路径上/子树中所有点的值。查询树上两点之间的路径上/子树中节点权值的和/极值/其它...

网友评论

      本文标题:5538. 统计子树中城市之间最大距离

      本文链接:https://www.haomeiwen.com/subject/vwjepktx.html