[ACM]【樹形DP/LIS/DFS/二分查找】Atcoder 165 LIS on Tree

LIS on Tree

傳送門
題意:一棵樹,每個節點有一個值,計算從1分別到其他點的途徑中,點權序列的最長子序列(LIS)長度。
在這裏插入圖片描述

思路:

LIS是典型的DP問題。關於計算LIS有兩種解法,一種O(N2)O(N^2),一種O(NlogN)O(N\log N)。後者運用了二分查找lower bound具體參考這個博客。dp[i]dp[i]記錄LIS第ii位元素的值。運用了貪心思想:最長遞增子序列必然是最後一位越小越好,這樣往後的數字能夠接上的可能更多。維護dp[i]dp[i]的過程,就是將新的數字替換lower bound的位置。如果新的數字大於dpdp所有數,就加在最後面。
然後就是使用DFS遍歷一次樹,就可以了。
那麼總共第一種方法O(N2)O(N^2),第二種O(NlogN)O(N\log N)

我一開始無比天真地使用了O(N2)O(N^2)的算法,對於每個樹節點,從根再回到當前節點一遍,計算dpdp…顯然是超時的,我真是太蠢了。
後來找到博客才知道還有二分查找的操作,真是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(n2)O(n^2)(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]);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章