【每日一题】Treepath

Treepath

http://www.nowcoder.com/questionTerminal/660faba350d74df095191ec3d321c15c

对于树上的点,只有深度为奇数的点走到深度为奇数的点和深度为偶数的点走到深度为偶数的点经过的边才会是偶数,dfs一边记录每个点的深度,统计深度为奇数的点的个数n和深度为偶数的点的个数m

ans = 图片说明

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5+10;
struct Node{
    int to,nex;
}e[N<<1];
int n,head[N],idx,depth[N];
int mx,cnt[N];//最大深度,深度为i的点有几个 
void add_edge(int u,int v){
    e[idx].to = v;
    e[idx].nex = head[u];
    head[u] = idx++;
}
void dfs(int u,int fa){
    depth[u] = depth[fa]+1;
    cnt[depth[u]]++;
    mx = max(mx,depth[u]); 
    for(int i = head[u];~i;i = e[i].nex){
        int v = e[i].to;
        if(v == fa) continue;
        dfs(v,u);
    }
}
int main(){
    scanf("%d",&n);
    memset(head,-1,sizeof(head));
    idx = 0;
    for(int i = 1;i < n;i++){
        int u,v;scanf("%d%d",&u,&v);
        add_edge(u,v);add_edge(v,u);
    }
    dfs(1,0);
    ll odd = 0,even = 0;//深度为奇数的点个数,深度为偶数的点的个数 
    for(int i = 1;i <= mx;i++){
        if(i&1) odd+=(1ll*cnt[i]);
        else even+=(1ll*cnt[i]);
    }
    ll res = odd*(odd-1)/2+even*(even-1)/2;
    printf("%lld\n",res);
    return 0;
}
全部评论

相关推荐

“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务