天天看點

QSC and Master HDU - 5900

點選打開連結

Problem Description Every school has some legends, Northeastern University is the same.

Enter from the north gate of Northeastern University,You are facing the main building of Northeastern University.Ninety-nine percent of the students have not been there,It is said that there is a monster in it.

QSCI am a curious NEU_ACMer,This is the story he told us.

It’s a certain period,QSCI am in a dark night, secretly sneaked into the East Building,hope to see the master.After a serious search,He finally saw the little master in a dark corner. The master said:

“You and I, we're interfacing.please solve my little puzzle!

There are N pairs of numbers,Each pair consists of a key and a value,Now you need to move out some of the pairs to get the score.You can move out two continuous pairs,if and only if their keys are non coprime(their gcd is not one).The final score you get is the sum of all pair’s value which be moved out. May I ask how many points you can get the most?

The answer you give is directly related to your final exam results~The young man~”

QSC is very sad when he told the story,He failed his linear algebra that year because he didn't work out the puzzle.

Could you solve this puzzle?

(Data range:1<=N<=300

1<=Ai.key<=1,000,000,000

0<Ai.value<=1,000,000,000)

Input First line contains a integer T,means there are T(1≤T≤10) test case。

  Each test case start with one integer N . Next line contains N integers,means Ai.key.Next line contains N integers,means Ai.value.

Output For each test case,output the max score you could get in a line.  

Sample Input

3 3 1 2 3 1 1 1 3 1 2 4 1 1 1 4 1 3 4 3 1 1 1 1  

Sample Output

0 2 0  

#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<algorithm>
#define bug(x) printf("%d***\n",x)

using namespace std;
typedef long long ll;

const int maxn=310;
ll dp[maxn][maxn];
ll id[maxn],val[maxn],sum[maxn]; 

ll gcd(ll a,ll b){
	return b==0?a:gcd(b,a%b);
}
/*
[i,j]的最佳狀态隻可能從  [i+1,j-1]轉移而來,可以想想中間是奇數的話,i,j不可能加上
中間是偶數的話,[i,j-1] [i+1,j]都是奇數,也不可能加上
但是[i,j]的取值有可能改變 
*/
int main(){
	int T;
//	freopen("123.txt","r",stdin);
	//freopen("456.txt","w",stdout);
	scanf("%d",&T);
	while(T--){
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%I64d",&id[i]);
		}
		for(int i=1;i<=n;i++){
			scanf("%I64d",&val[i]);
			sum[i]=sum[i-1]+val[i];//标記是否[i-j]區間全都取遍 
		}
		memset(dp,0,sizeof(dp));
		for(int j=2;j<=n;j++){
			for(int i=j-1;i>=1;i--){				
				if(i+1==j){
					if(gcd(id[i],id[j])!=1) dp[i][j]=val[i]+val[j];
					continue;
				}
				if(dp[i+1][j-1]==sum[j-1]-sum[i]&&gcd(id[i],id[j])!=1)
					dp[i][j]=max(dp[i+1][j-1],dp[i+1][j-1]+val[i]+val[j]);
				//為了取得不能完全取下所有值的最大值,要不然的話,ans隻能是0了 
				for(int k=i;k<j;k++){
					dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
				}
			}
		}
		printf("%I64d\n",dp[1][n]);
	}
	return 0;
}