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

链接: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();
     
}

猜你喜欢

转载自www.cnblogs.com/SuuT/p/8919872.html