牛客竞赛-Who killed Cock Robin
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. n\le 2\times 10^5n≤2×10
5
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
简而言之 计算我们能用多少种不同的方式从整个树中选择一个连通的子图。
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=2e5+10,mod=1e7+7;
#define int long long
int Next[N*2],head[N],go[N*2],tot;
inline void add(int u,int v){
Next[++tot]=head[u];head[u]=tot;go[tot]=v;
Next[++tot]=head[v];head[v]=tot;go[tot]=u;
}
int dp[N][2],n;
inline void dfs(int u,int fa){
dp[u][1]=1,dp[u][0]=0;
for(int i=head[u];i;i=Next[i]){
int v=go[i];
if(v==fa)continue;
dfs(v,u);
dp[u][0]=dp[u][0]+(dp[v][1]+dp[v][0])%mod;
dp[u][1]=(dp[u][1]*(dp[v][1]+1))%mod;
}
}
signed main(){
cin>>n;
for(int i=1,u,v;i<n;i++){scanf("%lld%lld",&u,&v);add(u,v);}
dfs(1,1);
cout<<(dp[1][1]+dp[1][0])%mod<<endl;
}