D. Who killed Cock Robin--“今日头条杯”首届湖北省大学程序设计竞赛(网络同步赛)

题目描述:链接点此

这套题的github地址(里面包含了数据,题解,现场排名):点此

题目描述

由于系统限制,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.    

.........

扫描二维码关注公众号,回复: 72042 查看本文章

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: 
 
题意说明:给你一个树,然后让你求树中的所有联通子树个数
 
树形dp
 
维护一个数组dp[i]表示以i为根节点且含有i的联通子图个数,然后从树的下层向上传递并进行计数,我们可以知道以当前节点的子节点为根节点且含有当前节点的子节点的联通子图个数,然后逐个遍历子节点并定义一个变量temp表示遍历过前面的子节点过后可以凑成的联通子图数,那么当遍历到新的一个子节点时,在以当前节点为根且使用当前遍历过所有子节点可以得到的新联通子图数为temp*dp[v],总联通子图数为temp*dp[v]+temp(v表示当前遍历的子节点),就这样逐个累计即可获得答案。
 
 代码:
/*
    data:2018.04.22
    author:gsw
    link:https://www.nowcoder.com/acm/contest/104#question
    tip:武大校赛--补题
*/
#define IO ios::sync_with_stdio(false);
#define ll long long
#define mod 10000007
#define maxn 200005

#include<iostream>
#include<string.h>
#include<math.h>
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int dp[maxn];
vector<int> g[maxn];
int a,b,n,ans=0;
void init()
{
    memset(dp,0,sizeof(dp));
}

void dfs(int node,int fa)
{
    ll t=1;
    for(int i=0;i<g[node].size();i++)
    {
        if(g[node][i]==fa)continue;
        dfs(g[node][i],node);
        t=(t+t*dp[g[node][i]])%mod;
    }
    dp[node]=t;
    ans=(ans+t)%mod;
}
int main()
{
    init();
    scanf("%d",&n);
    for(int i=0;i<n-1;i++)
    {
        scanf("%d%d",&a,&b);
        g[a].push_back(b);g[b].push_back(a);
    }
    dfs(1,0);
    printf("%d\n",ans);
}
 

猜你喜欢

转载自www.cnblogs.com/fantastic123/p/8952495.html