tjut 5900

#include <iostream>
#include<string.h>  
#include<vector>  
#include<queue>  
#include<algorithm>  
#include<stdio.h>  
#include<math.h>  
#include<map>  
#include<stdlib.h>  
#include<time.h>  
#include<stack>  
#include<set>  
using namespace std;  
typedef long long ll;  
ll a[310],b[310];  
ll dp[310][310];  
ll gcd(ll a,ll b)  
{  
    return b?gcd(b,a%b):a;  
}  
ll fdp(int x,int y)  //遞歸形式的區間dp
{  
    if(dp[x][y]!=-1)  //記憶化
        return dp[x][y];  
    if(x==y)  
        return dp[x][y]=0;  
    if(x>y)  //先考慮特殊情況
        return dp[x][y]=0;  
    ll tem=gcd(a[x],a[y]);  
    if(x+1==y&&tem!=1)  
        return dp[x][y]=b[x]+b[y];  
    if(x+1==y&&tem==1)  
        return dp[x][y]=0;  
    ll max0=0;  
    if(tem!=1)  
    {  
        ll ttt=fdp(x+1,y-1),tans=0;  
        for(int i=x+1; i<=y-1; i++)  
            tans+=b[i];  
        if(ttt==tans)  
            max0=b[x]+b[y]+ttt;  
    }  
    for(int i=x; i<y; i++)  
        max0=max(max0,fdp(x,i)+fdp(i+1,y));  
    return dp[x][y]=max0;  
}  
  
int main()  
{  
    int t;  
    scanf("%d",&t);  
    while(t--)  
    {  
        memset(dp,-1,sizeof(dp));  
        int n;  
        scanf("%d",&n);  
        for(int i=0; i<n; i++)  
            scanf("%I64d",&a[i]);  
        for(int i=0; i<n; i++)  
            scanf("%I64d",&b[i]);  
        ll ans=fdp(0,n-1);  
        printf("%I64d\n",ans);  
    }  
    return 0;  
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章