hdu5325 Crazy Bobo

Problem Description
Bobo has a tree,whose vertices are conveniently labeled by 1,2,...,n.Each node has a weight wi . All the weights are distrinct.
A set with m nodes v1,v2,...,vm is a Bobo Set if:
- The subgraph of his tree induced by this set is connected.
- After we sort these nodes in set by their weights in ascending order,we get u1,u2,...,um ,(that is, wui<wui+1 for i from 1 to m-1).For any node x in the path from ui to ui+1 (excluding ui and ui+1 ),should satisfy wx<wui .
Your task is to find the maximum size of Bobo Set in a given tree.
 

Input
The input consists of several tests. For each tests:
The first line contains a integer n ( 1n500000 ). Then following a line contains n integers w1,w2,...,wn ( 1wi109 ,all the wi is distrinct).Each of the following n-1 lines contain 2 integers ai and bi ,denoting an edge between vertices ai and bi ( 1ai,bin ).
The sum of n is not bigger than 800000.
 

Output
For each test output one line contains a integer,denoting the maximum size of Bobo Set.
 

Sample Input
  
  
7 3 30 350 100 200 300 400 1 2 2 3 3 4 4 5 5 6 6 7
 

Sample Output
  
  
5

题意:

n个点,每个点都有权值。n-1条边构成树。

求一个最大集合,使得集合中的所有点联通,且按照点的权值排列之后相邻两个点之间的路径上的点的权值都要比起点小。

思路:

题目转化为以一个点作为权值最小点,以权值递增的规则看它能到达多少个点。

将无向图建成有向图,权值小的点指向权值大的点。

使用dfs,进行记忆化搜索,num数组记录该点的子树节点数量。


代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#pragma comment(linker,"/STACK:1024000000,1024000000")
using namespace std;
const int maxn = 5e5+5;
int n;
int val[maxn];
int num[maxn], ans;

struct Edge{
    int to, next;
}edge[maxn];
int head[maxn], tot;
void addedge(int u, int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}

int dfs(int u)
{
    if(num[u]) return num[u];
    num[u] = 1;
    for(int i = head[u]; ~i; i = edge[i].next) {
        int v = edge[i].to;
        num[u] += dfs(v);
        ans = max(ans, num[u]);
    }
    return num[u];
}

int main()
{
    //freopen("in", "r", stdin);
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &val[i]);
            head[i] = -1;
            num[i] = 0;
        }

        tot = 0;
        int u, v;
        for(int i = 0; i < n-1; ++i) {
            scanf("%d %d", &u, &v);
            if(val[u] < val[v]) {
                addedge(u, v);
            }
            else {
                addedge(v, u);
            }
        }

        ans = 1;
        for(int i = 1; i <= n; ++i) {
            dfs(i);
        }
        printf("%d\n", ans);
    }
    return 0;
}




害羞

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值