zoukankan      html  css  js  c++  java
  • 数的重心模板

    #include <iostream>
    #include <string.h>
    #include <stdio.h>
    using namespace std;
    const int N = 20005;
    const int INF = 1<<30;
    int head[N],son[N],cnt,n,ans,size;
    bool vis[N];
    struct Edge{
        int to,next;
    }edge[2*N];
    
    void Init()
    {
        cnt = 0;
        size = INF;
        memset(vis,0,sizeof(vis));
        memset(head,-1,sizeof(head));
    }
    void add(int u,int v)
    {
        edge[cnt].to = v;
        edge[cnt].next = head[u];
        head[u] = cnt++;
    }
    void dfs(int cur)
    {
        vis[cur] = 1;
        son[cur] = 0;
        int tmp = 0;
        for(int i=head[cur];i>=0;i=edge[i].next)
        {
            int u = edge[i].to;
            if(!vis[u])
            {
                dfs(u);
                son[cur] += son[u] + 1;
                tmp = max(tmp,son[u] + 1);
            }
        }
        tmp = max(tmp,n-son[cur]-1);
        if(tmp < size || (tmp == size && cur < ans))
        {
            ans = cur;
            size = tmp;
        }
    }
    
    int main()
    {
        int T;
        scanf("%d",&T);
        while(T--)
        {
            Init();
            scanf("%d",&n);
            for(int i=1;i<=n-1;i++)
            {
                int u,v;
                scanf("%d%d",&u,&v);
                add(u,v);
                add(v,u);
            }
            dfs(1);
            printf("%d %d
    ",ans,size);
        }
        return 0;
    }
    
    


  • 相关阅读:
    [LeetCode]Reverse Linked List II
    [LeetCode]Move Zeroes
    Next Greater Element I
    Keyboard Row
    Number Complement
    SQL语句学习(二)
    SQL语句学习(一)
    jQuery学习(三)
    jQuery学习(二)
    JQuery学习(一)
  • 原文地址:https://www.cnblogs.com/ztz11/p/9190003.html
Copyright © 2011-2022 走看看