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.
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 ( 1≤n≤500000 ). Then following a line contains n integers w1,w2,...,wn ( 1≤wi≤109 ,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 ( 1≤ai,bi≤n ).
The sum of n is not bigger than 800000.
The first line contains a integer n ( 1≤n≤500000 ). Then following a line contains n integers w1,w2,...,wn ( 1≤wi≤109 ,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 ( 1≤ai,bi≤n ).
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;
}