zoukankan      html  css  js  c++  java
  • 树的重心

    寻找树的重心

    #include<cstdio>
    #include<cstdlib>
    #include<iostream>
    #define N 1000004
    #define inf 0x3f3f3f3f
    using namespace std;
    
    void read(int &s){
        char ch=getchar();int f=1;
        for(;!isdigit(ch);ch=getchar())if(ch='-')f=-1;
        for(s=0;isdigit(ch);s=s*10+ch-'0',ch=getchar());
        s*=f;
    }
    
    void print(int s){
        printf("%d
    ",s);
        return ;
    }
    
    int n;
    int siz[N];
    int son[N];
    int root,minl;
    
    struct Edge{
        int v,nxt;
    }e[N];
    int head[N],tot;
    
    void AddEdge(int u,int v){
        e[++tot].v=v;
        e[++tot].nxt=head[u];
        head[u]=tot;
        e[++tot].v=u;
        e[++tot].nxt=head[v];
        head[v]=tot;
    }
    
    void dfs(int node,int fa){
        for(int i=head[node];i;i=e[i].nxt){
            int to=e[i].v;
            if(to==fa)continue;
            dfs(to,node);
            siz[node]+=siz[to];
            son[node]=max(son[node],siz[to]);
        }
        son[node]=max(son[node],n-son[node]-1);
        if(son[node]<minl)minl=son[node],root=node;
        return ;
    }
    
    int main(){
        int a,b;
        minl=inf;
        read(n);
        for(int i=1;i<n;++i){
            read(a),read(b);AddEdge(a,b);
        }
        dfs(1,0);
        print(root);
        system("pause");
        return 0;
    }
    
  • 相关阅读:
    qsort()的使用
    c语言不寻常的类型转换(类型提升)
    堆栈段的三个主要用途
    区分 声明与定义
    宏定义陷阱与typedef
    约瑟夫环解决方案
    线程中断测试
    Redis
    本地缓存
    tomcat优化
  • 原文地址:https://www.cnblogs.com/qdscwyy/p/8178428.html
Copyright © 2011-2022 走看看