HDU 5423 Rikka with Tree (水)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5423

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
const int  maxn =1e3+5;
const int mod=9999991;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*
主要还是读懂题意吧,,,
读懂后不难发现,每一层最多只能有一个点,
最后一层除外。
*/
int n,a,b;
///前向星
struct node{
    int u,nxt;
}e[maxn<<1];
int head[maxn],dep[maxn],cnt[maxn],tot=0;
void init(){
    mst(head,-1),mst(dep,0);
    mst(cnt,0);
    tot=0;
}
void add(int x,int y){
    e[tot]=node{y,head[x]};
    head[x]=tot++;
}

void dfs(int u,int pre){
    if(pre!=-1) dep[u]=dep[pre]+1;
    for(int i=head[u],j=0;~i;i=e[i].nxt){
        int v=e[i].u;
        if(v==pre) continue;
        dfs(v,u);
        cnt[dep[v]]++;
    }
}

int main(){
    while(scanf("%d",&n)!=EOF){
        init();///初始化
        for(int i=1;i<n;i++){
            scanf("%d%d",&a,&b);
            add(a,b),add(b,a);
        }
        dep[1]=0;cnt[0]++;
        dfs(1,-1);
        sort(dep+1,dep+n+1);int tmp=dep[n];///最大深度
        int flag=1;for(int i=1;i<=n;i++) if(cnt[dep[i]]>1&&dep[i]!=tmp) flag=0;
        if(flag) puts("YES");
        else puts("NO");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/84075379