題目鏈接:Tweetuzki 愛序列
每個數字能到的數字最多隻有兩個。因爲每次是/3或者*2。說明數字是不重複的。也就是無環。
所以直接DAG最長路dp即可。
AC代碼:
#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
int n,a[N],mx,id; unordered_map<int,int> dp,vis,pre;
int dfs(int x){
if(dp[x]) return dp[x];
if(vis[x*2]) dp[x]=dfs(x*2)+1,pre[x]=x*2;
if(x%3==0&&vis[x/3]){
int tmp=dfs(x/3)+1;
if(tmp>dp[x]) dp[x]=tmp,pre[x]=x/3;
}
if(!dp[x]) dp[x]=1;
return dp[x];
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i],vis[a[i]]=1;
for(int i=1;i<=n;i++){
dfs(a[i]);
if(dp[a[i]]>mx) mx=dp[a[i]],id=a[i];
}
cout<<mx<<endl;
while(id) printf("%lld ",id),id=pre[id];
return 0;
}