来源:牛客网
题目描述
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
题解:
树形dp。递归到底,每个节点的值等于它所有相邻子节点的乘积,因为子树可以为空,
因此等于每个子节点的值加1在相乘。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=200005;
const ll mod=10000007;
vector<int>G[maxn];
ll a[maxn],ans=0;
bool vis[maxn];
void dfs(int s)
{
ll k=1;vis[s]=1;
for(int i=0;i<G[s].size();i++)
{
int to=G[s][i];
if(vis[to])continue;
dfs(to);
k=k*(a[to]+1)%mod;
}
a[s]=k%mod;
}
int main()
{
int n;scanf("%d",&n);
for(int i=1;i<n;i++)
{
int x,y;scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1);
for(int i=1;i<=n;i++)ans=(ans+a[i])%mod;
printf("%lld\n",ans);
return 0;
}