1 条题解

  • 1

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cmath>
    #include<set>
    #include<map>
    #include<queue>
    #include<stack>
    #include<vector>
    #include<cstring>
    #include<cstdlib>
    using namespace std;
    typedef long long ll;
    const int maxn=10000+5;
    const ll INF=0x3f3f3f3f3f3f3f3fll;
    int n;
    struct node{
    int from,to;
    }edge[maxn*2];
    int head[maxn*2];
    int cnt=0;
    void add(int u,int v){
    edge[++cnt].to=v;
    edge[cnt].from=head[u];
    head[u]=cnt;
    }
    ll ans=0;
    void dfs(int x,int fa,int deep,int tot){
    //当前访问节点为x 父节点为fa 访问深度为deep 访问节点个数为tot
    if(tot==n){ //如果n个节点都已经遍历过了 就返回
    return;
    }
    ans+=deep; //累加到答案里头
    //cout<<x<<endl;
    //cout<<deep<<endl;
    for(int i=head[x]; ~i; i=edge[i].from){ //链式前向星存储边集
    int v=edge[i].to; //存在一条x到v的边
    if(v!=fa){ //避免访问到父节点
    dfs(v,x,deep+1,tot+1); //v是x的子节点 继续访问 访问深度+1 访问节点数量+1
    }
    }
    }
    int main() {
    ios::sync_with_stdio(false);
    //freopen("卜算子.in","r",stdin);
    memset(head,-1,sizeof(head));
    cin>>n;
    int a,b;
    for(int i=1;i<=n-1;i++){
    cin>>a>>b;
    add(a,b);
    add(b,a); //双向边
    }
    int rt;
    cin>>rt; //输入根节点
    dfs(rt,-1,0,1); //从根节点开始建树,根节点的父节点设为-1 目前深度为0 已经遍历过的节点的个数为1
    cout<<ans;
    return 0;
    }
    啊其实我也不懂

  • 1

信息

ID
1227
难度
9
分类
(无)
标签
递交数
4
已通过
4
通过率
100%
上传者