Who killed Cock Robin(树形dp)

Who killed Cock Robin?

I, said the Sparrow, With my bow and arrow,I killed Cock Robin.

Who saw him die?

I, said the Fly.With my little eye,I saw him die.

Who caught his blood?

I, said the Fish,With my little dish,I caught his blood.

Who'll make his shroud?

I, said the Beetle,With my thread and needle,I'll make the shroud.    

.........

All the birds of the air

Fell a-sighing and a-sobbing.

When they heard the bell toll.

For poor Cock Robin.

March 26, 2018


Sparrows are a kind of gregarious animals,sometimes the relationship between them can be represented by a tree.

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.



输入描述:
The first line has a number n to indicate the number of sparrows. 

The next n-1 row has two numbers x and y per row, which means there is an undirected edge between x and y.

输出描述:
The output is only one integer, the answer module 10000007 (107+7) in a line



示例1
输入
4
1 2
2 3
3 4
输出
10


For a chain, there are ten different connected subgraphs:

题目大概:

由n个节点组成的树,每个结点都有一个值(不重复),求这颗树有多少颗不同的子树。

思路:

树形dp。

dp【i】是 以i为根,向下延伸的所有子树个数。

从叶子结点递推到根结点,每个结点初始值为1。

父亲节点由 dp【u】*(dp【v】+1)计算而来。因为不同联通块相连都会有不同的子树,所有要用乘法。


代码:


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn=2e5+10;
const int mod=1e7+7;
int n;
long long dp[maxn],a[maxn];
int sum=0;
struct poin
{
    int to,next;
}G[maxn*2];
int head[maxn*2],ans=0;
void add(int u,int v)
{
    G[ans].to=v;
    G[ans].next=head[u];
    head[u]=ans++;
}
void dfs(int d,int u,int fa)
{
    dp[u]=1;
    for(int i=head[u];i!=-1;i=G[i].next)
    {
        int v=G[i].to;
        if(v==fa)continue;
        dfs(d+1,v,u);
        dp[u]=((dp[u]%mod)*((dp[v]+1)%mod))%mod;
    }
    sum=(sum+dp[u])%mod;
}
int main()
{
    scanf("%d",&n);
    int u,v;
    memset(head,-1,sizeof(head));
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&u,&v);
        add(u,v);
        add(v,u);
    }
    dfs(0,1,0);
    printf("%d\n",sum%mod);
    return 0;
}







猜你喜欢

转载自blog.csdn.net/a1046765624/article/details/80042544