QSC and Master
傳送門1
傳送門2
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
題意
有n對二元組(key,value),兩個相鄰的元組間如果key不互質,那麼它們可以被移除,並獲得兩個元組中value值之和的分數。問最多能用多少分數。
分析
區間dp.定義dp[i][j]
表示在區間
CODE
#include<cstdio>
#include<memory.h>
#define FOR(i,a,b) for(int i=(a),i##_END_=(b);i<=i##_END_;i++)
#define N 305
typedef long long ll;
using namespace std;
int n;
bool mark[N][N];//表示該區間是否全部可以消掉
ll key[N],sum[N],val[N];
ll dp[N][N];
ll gcd(ll a,ll b) {return b==0?a:gcd(b,a%b);}
inline void Max(ll &x,ll y) {if(x<y)x=y;}
int main() {
int T;
scanf("%d",&T);
while(T--) {
memset(mark,0,sizeof mark);
memset(dp,0,sizeof dp);
sum[0]=0;
scanf("%d",&n);
FOR(i,1,n)scanf("%lld",&key[i]);
FOR(i,1,n) {
scanf("%lld",&val[i]);
sum[i]=sum[i-1]+val[i];
}
FOR(i,1,n)if(gcd(key[i],key[i-1])>1)mark[i][i-1]=1;
for(int len=2; len<=n; len+=2)FOR(L,1,n-len+1) {
int R=L+len-1;
if( (gcd(key[R-1],key[ R ])>1&&mark[ L ][R-2])||
(gcd(key[ L ],key[ R ])>1&&mark[L+1][R-1])||
(gcd(key[ L ],key[L+1])>1&&mark[L+2][ R ]))mark[L][R]=1;
}
FOR(len,2,n)FOR(L,1,n-len+1) {
int R=L+len-1;
if(mark[L][R])dp[L][R]=sum[R]-sum[L-1];
else FOR(k,L,R-1)Max(dp[L][R],dp[L][k]+dp[k+1][R]);
}
printf("%lld\n",dp[1][n]);
}
return 0;
}