D. Who killed Cock Robin 湖北省大学程序设计竞赛

本文介绍了一种计算树中所有子树数量的算法,通过深度优先搜索(DFS)和乘法原理来解决复杂关系下的子树计数问题,提供了一个具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://www.nowcoder.com/acm/contest/104/C
来源:牛客网

The Sparrow is for trial, at next bird assizes,we should select a connected subgraph from the whole tree of sparrows as trial objects.

Because the relationship between sparrows is too complex, so we want to leave this problem to you. And your task is to calculate how many different ways can we select a connected subgraph from the whole tree.

题意:给你一棵树,输出其所有子树的数量(连通块的数量)。

题解:手摸一下样例,再画一颗三叉树,找到一个公式:num[i]=(num[v1]+1)*(num[v2]+1)*````*(num[v0]+1) num[i]为以第i个节点为根的树的字数数量。v1```v0为其儿子。

    简单推导一下这个公式:对于n的每个儿子v,你选它时有num[v]种方法,、这是分步过程所以用乘法原理。但注意还有不选该儿子的一种情况,所以要+1.

    具体实现就是随便找一个点作为根dfs, 然后把所有num加起来

 

坑:我一发没过,改成ll 还是没过。比赛结束后发现 mod 没有改成ll orz

#define _CRT_SECURE_NO_WARNINGS
#include<cstring>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<string>
#include<stack>
#include<ctime>
#include<list>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<sstream>
#include<iostream>
#include<algorithm>
//#define INF 0x3f3f3f3f
#define eps 1e-6
#define pi acos(-1.0)
#define e exp(1.0)
#define rep(i,t,n)  for(int i =(t);i<=(n);++i)
#define per(i,n,t)  for(int i =(n);i>=(t);--i)
#define mp make_pair
#define pb push_back
//std::ios::sync_with_stdio(false);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
void smain();
#define ONLINE_JUDGE
int main() {
    ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    long _begin_time = clock();
#endif
    smain();
#ifndef ONLINE_JUDGE
    long _end_time = clock();
    printf("time = %ld ms.", _end_time - _begin_time);
#endif
    return 0;
}
const int maxn = 2e5 + 100;
const ll mod = 1e7 + 7;
const ll INF = (100000)*(200000ll) + 1000;
 
int n;
vector<int> E[maxn];
int num[maxn];
void dfs(int n,int fa) {
    if (num[n] != 1)return;
    int sz = E[n].size();
    if (sz == 1 && E[n][0] == fa) {
        num[n] = 1;
    }
    rep(i, 0, sz - 1) {
        int v = E[n][i];
        if (v ==fa)continue;
        dfs(v,n);
        num[n] = num[n]*(num[v] + 1)%mod;
    }
}
void Run() {
    dfs(1,0);
    int ans=0;
    rep(i,1,n) {
        ans = (ans + num[i]) % mod;
    }
    cout << ans << endl;
 
     
 
 
}
 
void smain() {
     
    cin >> n;
    rep(i,1,n-1) {
        int a, b;
        cin >> a >> b;
        E[a].pb(b);
        E[b].pb(a);
         
    }
    rep(i, 1, n)num[i] = 1;
    Run();
     
}

 

转载于:https://www.cnblogs.com/SuuT/p/8919872.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值