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 ;
}
const int maxn = 2e5 + ;
const ll mod = 1e7 + ;
const ll INF = ()*(200000ll) + ; int n;
vector<int> E[maxn];
int num[maxn];
void dfs(int n,int fa) {
if (num[n] != )return;
int sz = E[n].size();
if (sz == && E[n][] == fa) {
num[n] = ;
}
rep(i, , sz - ) {
int v = E[n][i];
if (v ==fa)continue;
dfs(v,n);
num[n] = num[n]*(num[v] + )%mod;
}
}
void Run() {
dfs(,);
int ans=;
rep(i,,n) {
ans = (ans + num[i]) % mod;
}
cout << ans << endl; } void smain() { cin >> n;
rep(i,,n-) {
int a, b;
cin >> a >> b;
E[a].pb(b);
E[b].pb(a); }
rep(i, , n)num[i] = ;
Run(); }
上一篇:如何查看linux系统的版本信息


下一篇:SQLLite 可以通过SQL语言来访问的文件型SQL数据库