hdu 5325 Crazy Bobo

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5325

题意:
n个点,每个点都有权值。n-1条边构成树。
求一个最大集合,使得集合中的所有点联通,且按照点的权值排列之后相邻两个点之间的路径上的点的权值都要比起点小。

思路:
题目转化为以一个点作为权值最小点,以权值递增的规则看它能到达多少个点。
将无向图建成有向图,权值小的点指向权值大的点。
使用dfs,进行记忆化搜索,num数组记录该点的子树节点数量。

代码:(需要手动扩栈)

#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <assert.h>
#pragma comment(linker,"/STACK:1024000000,1024000000")  
using namespace std;

template <class T>

inline bool scan_d(T &ret)
{
    char c; int sgn;
    if (c = getchar(), c == EOF) return 0; //EOF  
    while (c != '-' && (c<'0' || c>'9')) c = getchar();
    sgn = (c == '-') ? -1 : 1;
    ret = (c == '-') ? 0 : (c - '0');
    while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
    ret *= sgn;
    return 1;
}

const int MAXN = 500010;
int  n;
int a[MAXN];
int ans;

struct Edge
{
    int to;
    int 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 num[MAXN];// 记录点i为set最小值的时候i可以到达的点的数目

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

int main()
{
    while (~scanf("%d", &n))
    {
        tot = 0;
        for (int i = 1; i <= n; i++)
        {
            scan_d(a[i]);
            head[i] = -1;
            num[i] = 0;
        }
        int x, y;
        for (int i = 1; i < n; i++)
        {
            scan_d(x);
            scan_d(y);
            if (a[x] > a[y])
                addedge(y, x);
            else 
                addedge(x, y);
        }
        ans = 0;
        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、付费专栏及课程。

余额充值