zoukankan      html  css  js  c++  java
  • poj 3107 树重心

    http://acm.hust.edu.cn/vjudge/problem/18069

    和poj 1655差不多:http://www.cnblogs.com/qlky/p/5780933.html

    区别就是要记录所有的重心

    #include <iostream>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <cctype>
    #include <vector>
    #include <iterator>
    #include <set>
    #include <map>
    #include <sstream>
    using namespace std;
    
    #define mem(a,b) memset(a,b,sizeof(a))
    #define pf printf
    #define sf scanf
    #define spf sprintf
    #define pb push_back
    #define debug printf("!
    ")
    #define MAXN 50000+5
    #define MAX(a,b) a>b?a:b
    #define blank pf("
    ")
    #define LL long long
    #define ALL(x) x.begin(),x.end()
    #define INS(x) inserter(x,x.begin())
    #define pqueue priority_queue
    #define INF 0x3f3f3f3f
    
    #define ls (rt<<1)
    #define rs (rt<<1|1)
    
    int n,m;
    
    int ptr = 1,head[MAXN],vis[MAXN];
    
    int res,ans[MAXN],son[MAXN],num=0;
    
    struct node
    {
        int y,val,next;
    }tree[MAXN<<1];
    
    void add(int fa,int son)
    {
        tree[ptr].y = son;
        tree[ptr].next = head[fa];
        head[fa] = ptr++;
    }
    
    void dfs(int root)
    {
        vis[root] = 1;
        son[root] = 0;
        int tmp = 0;
        for(int i=head[root];i!=-1;i=tree[i].next)
        {
            int y = tree[i].y;
            if(vis[y]) continue;
            dfs(y);
            son[root] += son[y]+1;
            tmp = max(son[y]+1,tmp);
        }
        tmp = max(tmp,n-son[root]-1);
        if(tmp<res)
        {
            ans[0] = root;
            num = 1;
            res = tmp;
        }
        else if(tmp == res) ans[num++] = root;
    }
    
    
    int main()
    {
        int i,j,t,kase=1;
        while(~sf("%d",&n))
        {
            mem(tree,0);
            mem(head,-1);
            mem(vis,0);
            mem(ans,0);
            res=INF;
            ptr = 1;
            num = 0;
            int x,y;
            for(i=1;i<n;i++)
            {
                sf("%d%d",&x,&y);
                add(x,y);
                add(y,x);
            }
            dfs(1);
            sort(ans,ans+num);
            pf("%d",ans[0]);
            for(i=1;i<num;i++) pf(" %d",ans[i]);
            blank;
        }
        return 0;
    }
  • 相关阅读:
    笔记35 跨重定向请求传递数
    判断邮箱的正则表达式
    按钮
    async await 的用法
    笔记34 Spring MVC的高级技术——处理multipart形式的数据
    Convert Sorted Array to Binary Search Tree
    Binary Tree Zigzag Level Order Traversal
    Unique Binary Search Trees,Unique Binary Search Trees II
    Validate Binary Search Tree
    Populating Next Right Pointers in Each Node,Populating Next Right Pointers in Each Node II
  • 原文地址:https://www.cnblogs.com/qlky/p/5781016.html
Copyright © 2011-2022 走看看