“今日头条杯”首届湖北省大学程序设计竞赛(网络同步赛)C题

链接: https://www.nowcoder.com/acm/contest/104/C
来源:牛客网

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

我们搜每一点后返回的值就相当于以这个点为起点的所有的子联通,难就难在如果父节点

有多个子节点应该怎么办,解决的办法是遍历每个节点时temp=temp*(dfs(vec[x][i],x)+1);

为了不搜回去,搜索时保存父节点。

AC代码 

#include<iostream>
#include<vector>
#include<stdio.h>
#define LL long long
#define maxn 200005
#define mod 10000007
using namespace std;
int n;
vector<LL>vec[maxn];
int x,y;
LL ans;
LL dfs(int x,int pre)
{
    LL temp=1;
    for(int i=0;i<vec[x].size();i++)
    {
        if(vec[x][i]==pre)
            continue;
        temp=temp*(dfs(vec[x][i],x)+1);
        temp=temp%mod;
    }
    ans=(ans+temp)%mod;
    return temp;
}
int main()
{
    scanf("%d",&n);
    ans=0;
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&x,&y);
        vec[x].push_back(y);
        vec[y].push_back(x);
    }
    dfs(1,0);
    printf("%lld\n",ans);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值