Topic description
Enter description:
Each input contains 1 test case. The first line of each test data contains an
integer n (1 <= n <= 50), which represents the number of students, and the next line contains n integers, which represent the ability value ai of each student in order (- 50 <= ai <= 50). The next line contains two integers, k and d (1 <= k <= 10, 1 <= d <= 50).
Output description:
One line of output represents the largest product.
enter
3 7 4 7 2 50
output
49
Analysis: This problem is implemented using dynamic programming because of the optimal substructure property.
Problem decomposition: Decomposition is the key, let f(n, k) mean that the last person is selected from n people first, and then k-1 people are selected from the remaining n-1 people, and let this one and the previous k -1 meets the constraints
Mathematical description [find the recursive formula]: a[end]>0 f(end,k)=max{f(then,k-1)}*a[end]} (max(k-1,end-d)= <then<=end-1)
a[end]<0 f(end,k)=max{g(then,k-1)}*a[end]} (max(k-1,end-d)=<then<=end-1) //Because the ability value has a negative value, an additional array g[][] is added to store the minimum value of the product
Recursive transformation:
f(end,k)=max{f(then,k-1)*a[end],g(then,k-1)*a[end] (max(k-1,end-d)=<then<=end-1)
g(end,k)=min{f(then,k-1)*a[end],g(then,k-1)*a[end] (max(k-1,end-d)=<then<=end-1)
Note: The value of this question should be stored in the long type.
My code implementation:
1 #include<stdio.h> 2 #include<math.h> 3 #include<limits.h> 4 #define N 100 5 int a[N]; 6 long f[N][N],g[N][N]; 7 8 int max1(int a,int b){ 9 return a>b?a:b; 10 } 11 12 long max(long a,long b){ 13 return a>b?a:b; 14 } 15 16 long min(long a,long b){ 17 return a<b?a:b; 18 } 19 void ability(int n,int kk,int d){ 20 for(int i=1;i<=n;i++){ 21 f[i][1]=a[i]; 22 g[i][1]=a[i]; 23 } 24 for(long k=2;k<=kk;k++){ 25 for(int end=k;end<=n;end++){ 26 long tempmax=INT_MIN; 27 long tempmin=INT_MAX; 28 for(int then=max1(k-1,end-d);then<=end-1;then++){ 29 if(tempmax<max(f[then][k-1]*a[end],g[then][k-1]*a[end])) 30 tempmax=max(f[then][k-1]*a[end],g[then][k-1]*a[end]); 31 if(tempmin>min(f[then][k-1]*a[end],g[then][k-1]*a[end])) 32 tempmin=min(f[then][k-1]*a[end],g[then][k-1]*a[end]); 33 } 34 f[end][k]=tempmax; 35 g[end][k]=tempmin; 36 } 37 } 38 } 39 40 int main(){ 41 int n,k,d; 42 scanf("%d",&n); 43 for(int i=1;i<=n;i++) 44 scanf("%d",&a[i]); 45 scanf("%d%d",&k,&d); 46 ability(n,k,d); 47 long result=INT_MIN; 48 for(int i=k;i<=n;i++){ 49 if(result<f[i][k])result=f[i][k]; 50 } 51 printf("%ld",result); 52 53 return 0; 54 }