• 51Nod2602 树的直径


    Problem

    一棵树的直径就是这棵树上存在的最长路径。现在有一棵n个节点的树,现在想知道这棵树的直径包含的边的个数是多少?

    Solution

    随便找一个点,找最远的,再找新的点最远的。

    当然我瞎搞的树状dp,子树分支最大的和次大的加起来就行。

    Code

    #include<stdio.h>
    #include<set>
    #include<iostream>
    #include<stack>
    #include<cstring>
    #include<cmath>
    #include<vector>
    #include<algorithm>
    typedef long long ll;
    typedef long double ld;
    typedef double db;
    #define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
    using namespace std;
    const int mod=998244353;
    int mo(ll a,int p){
        return a>=p?a%p:a;
    }
    inline int rd() {
        int x = 0, f = 1;
        char ch;
        while (ch < '0' || ch > '9') {
            if (ch == '-')f = -1;
            ch = getchar();
        }
        while (ch >= '0' && ch <= '9') {
            x = x * 10 + ch - '0';
            ch = getchar();
        }
        return f * x;
    }
    int n,ans;
    struct E{
        int u,v,nex;
    }e[200020];
    int g[100020];
    int f[100020];
    int dfs(int x){
        int mx1=0,mx2=0;
        for(int i=g[x];i>0;i=e[i].nex){
            if(!f[e[i].v]){
                f[e[i].v]=1;
                int d=dfs(e[i].v);
                f[e[i].v]=0;
                if(!mx1){
                    mx1=d;
                }
                else if(!mx2){
                    mx2=d;
                    if(mx2>mx1) swap(mx1,mx2);
                }
                else{
                    if(d>mx2) mx2=d;
                    if(mx2>mx1) swap(mx1,mx2);
                }
            }
        }
        ans=max(ans,mx1+mx2+1);
        if(!mx1&&!mx2){
            return 1;
        }
        return mx1+1;
    }
    int main(){
        //io_opt;
        n=rd();
        int x,y;
        for(int i=1;i<=n-1;i++){
            x=rd(),y=rd();
            e[i]=(E){x,y,g[x]};g[x]=i;
            e[i+n-1]=(E){y,x,g[y]};g[y]=i+n-1;
        }
        f[1]=1;
        dfs(1);
        printf("%d
    ",ans-1);
        return 0;
    }
    
  • 相关阅读:
    nginx&http 第二章 ngx 事件event处理 数据结构
    nginx&http 第二章 ngx启动多进程
    PF_PACKET抓包mmap
    PF_PACKET&&tcpdump
    tcpack--3快速确认模式- ack状态发送&清除
    tcpack---1简述
    tcpack--3快速确认模式
    tcpack--4延时ack
    linux tcp Nagle算法,TCP_NODELAY和TCP_CORK 转载
    tcpack----- 2sack dack
  • 原文地址:https://www.cnblogs.com/sz-wcc/p/11761309.html
Copyright © 2020-2023  润新知