牛客练习赛9。 B 柯朵莉的值域连续端

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

珂朵莉给你一个有根树,求有多少个子树满足其内部节点编号在值域上连续 

一些数在值域上连续的意思即其在值域上构成一个连续的区间 

输入描述:

第一行有一个整数n,表示树的节点数。
接下来n–1行,每行两个整数x,y,表示存在一条从x到y的有向边。
输入保证是一棵有根树。

输出描述:

输出一个数表示答案
示例1

输入

5
2 3
2 1
2 4
4 5

输出

5

说明

节点1子树中编号为1,值域连续
节点3子树中编号为3,值域连续
节点5子树中编号为5,值域连续
节点4子树中编号为4,5,值域连续
节点2子树中编号为1,2,3,4,5,值域连续

备注:

对于100%的数据,有n <=100000
 
 给的树是一个有根数,即根节点的indegree[root] == 0; 另外这个题的数据比较规整,是从1到n,并没有相同的数。。。 
所以就耍了个小聪明,用dfs,过程中更新结点的区间,然后区间数等于子结点树。。。

还有就是,抽到了卫衣贼他妈开心hhhhhhh

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <cmath>
#include <queue>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <string>
#include <utility>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 100050;
struct Node {
    int v, next;
}node[maxn * 3];
int head[maxn], total;
int res;
int indegree[maxn];
void init() {
    memset(indegree, 0, sizeof(indegree));
    res = 0;
    total = 0;
    memset(head, -1, sizeof(head));
}

void add(int u, int v) {
    node[total] = {v, head[u]};
    head[u] = total++;
}

int son[maxn];
pair<int, int> dfs(int fa, int u) {
    pair<int, int> a{u, u};
    son[u] = 1;
    for (int i = head[u]; i != -1; i = node[i].next) {
        int v = node[i].v;
        if (v != fa) {
            auto t = dfs(u, v);
            a.first = min(a.first, t.first);
            a.second = max(a.second, t.second);
            son[u] += son[v];
        }
    }
    //cout << fa << "    "  << u << "    "  << son[u] << endl;
    if (a.second - a.first + 1 == son[u])
        res++;
    return a;
}

int main() {
    //freopen("in.txt", "r", stdin);
    init();
    int n;
    cin >> n;
    for (int i = 1; i < n; ++i) {
        int u, v;
        cin >> u >> v;
        indegree[v]++;
        add(u, v);
    }
    int root;
    for(int i = 1; i <= n; ++i) {
        if (!indegree[i]) {
            root = i;
            break;
        }
    }
    dfs(-1, root);
    cout << res << endl;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值