时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
由于系统限制,C题无法在此评测,此题为现场赛的D题
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表示n个结点,接下来n-1行每行输入x、y表示x和y之间存在无向边,求整棵树(不存在环)中连接子图的种数
这题想了很久,但实现不出来,下面是来自同学的解题思路(很赞):
根据输入建立无向图,再以1为根节点建树,设f(i)为以i为根的连接子图种数,假设i有k个子节点,那么f(i)=Π(f(j)+1) (0<=j<k) (连续乘积),加1的情况表示不选该子结点,ans=Σf(i)
#include<bits/stdc++.h>
using namespace std;
const int maxn=200005;
const int mod=1e7+7;
typedef long long LL;
int n;
vector<int>s[maxn];//s[i]储存i的子节点
int pre[maxn];//pre[i]表示i的父节点
int dp[maxn];//dp[i]用来储存f(i)
int f(int u)
{
if(dp[u]) return dp[u];
if(s[u].size()==0) return 1;
LL cnt=1;
for(int i=0;i<s[u].size();i++)
{
if(s[u][i]==pre[u]) continue;
cnt=(cnt*(f(s[u][i])+1))%mod;
}
dp[u]=cnt;
return cnt;
}
void build_tree(int u)//递归建树
{
for(int i=0;i<s[u].size();i++)
{
if(s[u][i]==pre[u]) continue;//父节点跳过
pre[s[u][i]]=u;
build_tree(s[u][i]);
}
}
int main()
{
scanf("%d",&n);
int x,y;
LL ans=0;
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
s[x].push_back(y);
s[y].push_back(x);
}
memset(pre,0,sizeof(pre));
memset(dp,0,sizeof(dp));
build_tree(1);
for(int i=1;i<=n;i++) {int h=f(i);ans=(ans+f(i))%mod;}
ans%=mod;
printf("%lld\n",ans);
return 0;
}