LIS on Tree
传送门
题意:一棵树,每个节点有一个值,计算从1分别到其他点的途径中,点权序列的最长子序列(LIS)长度。
思路:
LIS是典型的DP问题。关于计算LIS有两种解法,一种
O
(
N
2
)
O(N^2)
O(N2),一种
O
(
N
log
N
)
O(N\log N)
O(NlogN)。后者运用了二分查找lower bound。具体参考这个博客。
d
p
[
i
]
dp[i]
dp[i]记录LIS第
i
i
i位元素的值。运用了贪心思想:最长递增子序列必然是最后一位越小越好,这样往后的数字能够接上的可能更多。维护
d
p
[
i
]
dp[i]
dp[i]的过程,就是将新的数字替换lower bound的位置。如果新的数字大于
d
p
dp
dp所有数,就加在最后面。
然后就是使用DFS遍历一次树,就可以了。
那么总共第一种方法
O
(
N
2
)
O(N^2)
O(N2),第二种
O
(
N
log
N
)
O(N\log N)
O(NlogN)。
我一开始无比天真地使用了
O
(
N
2
)
O(N^2)
O(N2)的算法,对于每个树节点,从根再回到当前节点一遍,计算
d
p
dp
dp…显然是超时的,我真是太蠢了。
后来找到博客才知道还有二分查找的操作,真是tql。(记得回溯啊)
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=200005;
int a[maxn],tot=0;//a记录点权
int dp[maxn],head[maxn];
int ans[maxn];//记录长度
struct node{
int next,to;
}edge[maxn*2];//注意这里一定要两倍TAT 不然RE
void add_edge(int u,int v){
tot++;
edge[tot].next=head[u];
edge[tot].to=v;
head[u]=tot;
}
//lower bound
int binary_search(int low,int high,int key){
int mid,ans=1;
while(low<=high){
mid=(high+low)>>1;
if(dp[mid]>=key) ans=mid,high=mid-1;
else low=mid+1;
}
return ans;
}
void dfs(int u,int fa,int pos){
int pre,tmp;//pre用于回溯,更改过dp数组记得变回去!
if(dp[pos]<a[u]) pos++,tmp=pos;//如果大于dp所有数
else tmp=binary_search(1,pos,a[u]);
pre=dp[tmp];
dp[tmp]=a[u];//更改
ans[u]=pos;//记录答案(长度)
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].to;
if(v==fa) continue;
dfs(v,u,pos);
}
dp[tmp]=pre;//回溯
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=n-1;i++){
int tmp,tmp2;
scanf("%d%d",&tmp,&tmp2);
add_edge(tmp,tmp2);
add_edge(tmp2,tmp);
}
dp[1]=a[1];//初始化,不然都是0找不到lower bound
//当然也可以选择直接memset(dp,0x3f,sizeof(dp));
dfs(1,0,1);
for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
}
贴一个vector+lower_bound(STL)的操作:
以及这位大佬的具体代码
int pos = lower_bound(all(dp),a[v])-dp.begin();
再贴一个
O
(
n
2
)
O(n^2)
O(n2)(TLE)的做法:
运用了vector。学会了pop_back操作嘿嘿。
#include<bits/stdc++.h>
using namespace std;
const int maxn=200004;
int head[maxn],tot=0;
int a[maxn];
int dp[maxn];
vector<int> G;
struct node{
int next,to;
}edge[maxn*2];
void add_edge(int u,int v){
tot++;
edge[tot].next=head[u];
edge[tot].to=v;
head[u]=tot;
}
void dfs(int u,int fa){
dp[u]=1;
for(auto i:G){
if(a[i]<a[u]) dp[u]=max(dp[i]+1,dp[u]);
}
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].to;
if(v==fa) continue;
G.push_back(v);
dfs(v,u);
G.pop_back();
}
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=n-1;i++){
int tmp,tmp2;
scanf("%d%d",&tmp,&tmp2);
add_edge(tmp,tmp2);
add_edge(tmp2,tmp);
}
G.push_back(1);
dfs(1,0);
for(int i=1;i<=n;i++) printf("%d\n",dp[i]);
}