zoukankan      html  css  js  c++  java
  • CF1453E Dog Snacks(贪心)

    第一步,可以贪心的发现,在子树中,如果有多个儿子,那么先走深的儿子,因为最后要跳到上面父亲去,因此最后所在的地方约浅越好

    但是对于根来说,如果他有多个子树,那么先走浅的好,因为我最后一步不需要跳到别的子树,只需要跳回根就行,如果先走最深的子树,那么要跳到别的子树,就不是最优的

    因为他最深

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    typedef pair<int,int> pll;
    typedef pair<int,int> plll;
    const int N=4e5+10;
    const int inf=0x3f3f3f3f;
    int n,h[N],ne[N],e[N],idx;
    int res;
    int f[N];
    void add(int a,int b){
        e[idx]=b,ne[idx]=h[a],h[a]=idx++;
    }
    void dfs(int u,int fa){
        int i;
        int mx=0;
        int cnt=0;
        int mx1=0;
        for(i=h[u];i!=-1;i=ne[i]){
            int j=e[i];
            if(j==fa)
                continue;
            dfs(j,u);
            cnt++;
            f[u]=min(f[u],f[j]+1);
            if(f[j]+1>mx){
                mx1=mx;
                mx=f[j]+1;
            }
            else if(f[j]+1>mx1){
                mx1=f[j]+1;
            }
        }
        if(cnt==0){
            f[u]=0;
            return ;
        }
        if(u==1){
            if(cnt==1){
                res=max(res,mx);
            }
            else{
                res=max(res,mx);
                res=max(res,mx1+1);
            }
        }
        else{
            if(cnt>=2)
            res=max(res,mx+1);
        }
    }
    int main(){
        ios::sync_with_stdio(false);
        int t;
        cin>>t;
        while(t--){
            cin>>n;
            int i;
            res=0;
            for(i=1;i<=n;i++){
                h[i]=-1;
                f[i]=0x3f3f3f3f;
            }
            for(i=1;i<n;i++){
                int a,b;
                cin>>a>>b;
                add(a,b);
                add(b,a);
            }
            dfs(1,-1);
            cout<<res<<endl;
        }
        return 0;
    }
    View Code
  • 相关阅读:
    1144 The Missing Number (20分)
    1145 Hashing
    1146 Topological Order (25分)
    1147 Heaps (30分)
    1148 Werewolf
    1149 Dangerous Goods Packaging (25分)
    TypeReference
    Supervisor安装与配置()二
    谷粒商城ES调用(十九)
    Found interface org.elasticsearch.common.bytes.BytesReference, but class was expected
  • 原文地址:https://www.cnblogs.com/ctyakwf/p/14101770.html
Copyright © 2011-2022 走看看