题目:
题意:
给出 n n n个节点的 k e y key key和 v a l val val,需要我们构建一棵二叉查找树,在保证任意两个相邻的点的 g c d ( k e y i , k e y j ) ≠ 1 gcd(key_i,key_j) \neq 1 gcd(keyi,keyj)̸=1的情况下, ∑ i = 1 n s u m i \sum_{i=1}^nsum_i ∑i=1nsumi最大是多少
分析:
我们先预处理每个点与其他点的
g
c
d
gcd
gcd,然后枚举一个根节点,再进行区间
d
p
dp
dp
因为左子树和右子树是互不干扰的,所以我们再在左子树中选出一个节点与根节点相连,当前子树以
t
a
ta
ta为根,右子树同理
代码:
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#define LZX Mu
#define LL long long
using namespace std;
inline LL read() {
LL d=0,f=1;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
return d*f;
}
struct node{
LL k,v;
}e[305];
LL sum[305],g[305][305],f[305][305][3];
bool cmp(node x,node y) {return x.k<y.k;}
void dp(LL l,LL r,LL id)
{
if(l>r) return;
if(f[l][r][id]) return;
LL root=(id==1?r+1:l-1);
for(LL i=l;i<=r;i++)
{
if(g[i][root]==1) continue;
dp(l,i-1,1);dp(i+1,r,2);
if(f[l][i-1][1]<0||f[i+1][r][2]<0) continue;
f[l][r][id]=max(f[l][r][id],f[l][i-1][1]+f[i+1][r][2]+sum[r]-sum[l-1]);
}
if(!f[l][r][id]) f[l][r][id]=-1;
return;
}
int main()
{
// freopen("tree.in","r",stdin);
// freopen("tree.out","w",stdout);
LL n=read();
for(LL i=1;i<=n;i++) e[i].k=read(),e[i].v=read();
sort(e+1,e+1+n,cmp);
for(LL i=1;i<=n;i++) sum[i]=sum[i-1]+e[i].v;
for(LL i=1;i<=n;i++)
for(LL j=1;j<=n;j++)
g[i][j]=__gcd(e[i].k,e[j].k);
LL ans=-1;
for(LL i=1;i<=n;i++)
{
dp(1,i-1,1);dp(i+1,n,2);
if(f[1][i-1][1]<0||f[i+1][n][2]<0) continue;
ans=max(ans,f[1][i-1][1]+f[i+1][n][2]+sum[n]);
}
cout<<ans;
return 0;
}